HTML5 required, open collapse and focus required element if empty

前端 未结 2 751
伪装坚强ぢ
伪装坚强ぢ 2021-01-28 13:08

I am trying to get the page to focus on an empty element, if its within a collapsed div it will then open that element and focus on the required field which was empty. I am usin

相关标签:
2条回答
  • 2021-01-28 13:55

    Why not use some good ol' coding yourself ;)

    I've updated the css and added some JS. I hope it fits your needs.

    CSS:

    .panel-collapse {
      margin-top: 20px;
      max-height: 200px;
      -webkit-transition: all 0.6s ease-in-out;
      -moz-transition: all 0.6s ease-in-out;
      -o-transition: all 0.6s ease-in-out;
      transition: all 0.6s ease-in-out;
      overflow-y: hidden;
      display: block;
    }
    
    .collapse {
      max-height:0;
      display:block;
      margin: 0 !important;
    }
    

    JS:

    $(document).ready(function(){
        var validated = false,
            inputC = 0,
            that;
      jQuery.fn.extend({
        valVal: function() {
          return $(this).each(function() {
            var input = $(this);
            inputC++;
            if(!$.trim(input.val())){
                input.closest(".collapse").removeClass("collapse");
            }
          });
        }
      });
    
        $(".savechanges").on("click", function(){
        that = $(this);
        console.log(that.parent());
        inputC = 0;
        $(".panel-collapse").addClass("collapse");
        that.parent().parent().find("input").valVal();
        var collapse = $(".collapse");
        if(collapse.length==inputC){
            validated = true;
          console.log("yess");
          //Do an AJAX request to server.
        }else{
          console.log("not quite correct yet..");
          //Just for the sample, has no use (yet) in this piece of code
        }
    
      })
        $(".panel-heading").on("click", function(){
        that = $(this);
        that.parent().find(".panel-collapse").toggleClass("collapse");
        that.parent().find("input").focus();
      })
    })
    

    And here is a working JSFiddle

    Good luck!

    0 讨论(0)
  • 2021-01-28 13:59

    Add a listener to your inputs for them being invalid, then tell the parent container to open.

    var inputs = document.querySelectorAll('form div input');
    
    [].forEach.call(inputs, function(input) {
      input.addEventListener('invalid',function(e){
        input.parentNode.style.display = 'block'
      });
    });
    div {
      display: none;
    }
    <form>
      <div>
        <input name="one" type="text" required />
      </div>
      <div>
        <input name="two" type="text" required />
      </div>
      <input type="submit" value="submit" />
    </form>

    0 讨论(0)
提交回复
热议问题