Force user to fill all fields before enabling form submit

前端 未结 12 2042
忘掉有多难
忘掉有多难 2021-02-07 00:49

I have a form containing various fields.

See jsFiddle demo.

My aim is to enable the submit button only when the user has filled in all fields.

So far,

相关标签:
12条回答
  • 2021-02-07 01:39
    • Make the changes take effect after changing inputs values:

    On each input change, test the values of other inputs and checked state of radio, if all inputs has been entered it will make the submit button enabled:

    var validateInputs = function validateInputs(inputs) {
      var validForm = true;
      inputs.each(function(index) {
        var input = $(this);
        if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
          $("#subnewtide").attr("disabled", "disabled");
          validForm = false;
        }
      });
      return validForm;
    }
    
    inputs.change(function() {
      if (validateInputs(inputs)) {
        $("#subnewtide").removeAttr("disabled");
      }
    });
    

    Demo:

    var inputs = $("form#myForm input, form#myForm textarea");
    
    var validateInputs = function validateInputs(inputs) {
      var validForm = true;
      inputs.each(function(index) {
        var input = $(this);
        if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
          $("#subnewtide").attr("disabled", "disabled");
          validForm = false;
        }
      });
      return validForm;
    }
    
    
    inputs.change(function() {
      if (validateInputs(inputs)) {
        $("#subnewtide").removeAttr("disabled");
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="#" method="post" id="myForm">
    
      Title:
      <input id="titlenewtide" type="text" name="title" required>
      <br>Description:
      <textarea name="description" id="description"></textarea>
      <br>Tag:
      <input id="newtag" type="text" name="newtag" required>
      <br>Category:
      <input type="radio" name="category" value="19" required>Animation
      <button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
    
    </form>

    Also it uses the form id="myForm", so you can use it to validate only specific forms in your pages.

    Note: This is tested and working on Chrome, Firefox and IE.


    EDIT:

    • Make the changes take effect when we type in the inputs:

    In the previous code we are using onchange event handler to call the function so it's only called when we click outside a given input (after change).

    To perform the call automatically when the user enters a character in a field (the last one) we need to use the onkeyup event so we don't need to click outside of it.

    This is the changed code you need :

        var inputs = $("form#myForm input, form#myForm textarea");
    
        var validateInputs = function validateInputs(inputs) {
          var validForm = true;
          inputs.each(function(index) {
            var input = $(this);
            if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
              $("#subnewtide").attr("disabled", "disabled");
              validForm = false;
            }
          });
          return validForm;
        }
    
    
        inputs.each(function() {
          var input = $(this);
          if (input.type === "radio") {
            input.change(function() {
              if (validateInputs(inputs)) {
                $("#subnewtide").removeAttr("disabled");
              }
            });
          } else {
            input.keyup(function() {
              if (validateInputs(inputs)) {
                $("#subnewtide").removeAttr("disabled");
              }
            });
          }
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="#" method="post" id="myForm">
    
      Title:
      <input id="titlenewtide" type="text" name="title" required>
      <br>Description:
      <textarea name="description" id="description"></textarea>
      <br>Tag:
      <input id="newtag" type="text" name="newtag" required>
      <br>Category:
      <input type="radio" name="category" value="19" required>Animation
      <button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
    
    </form>

    0 讨论(0)
  • 2021-02-07 01:46
    Use this html<br>
    HTML:
    <br>
    <pre>
    <form action="#" method="post" id="">
            Title: ##<input id="titlenewtide" type="text" name="title" required> 
            Description: <textarea name="description" id="description"></textarea>
            Tag:  <input id="newtag" type="text" name="newtag" required> 
            Category: <input type="checkbox" onclick="validate()" name="category" id="cate"value="19" required > Animation
            <button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
    
    </form>
    </pre>
    validation code:<br>
    //on each key up function intiate the function validate
    <pre>
        jQuery("input[type='text']").on("keyup", function () {
            validate();
        });
        jQuery("#description").on("keyup", function () {
            validate();
        });
    
        function validate(){
         jQuery("input[type='text']").each(function(){
    
            if (jQuery(this).val() != "" )
            {
                if((jQuery("#description").val() !="") && (jQuery("#cate").is(':checked')))
                {
    
                    jQuery("#subnewtide").removeAttr("disabled"); 
                }
                else {
                    jQuery("#subnewtide").attr("disabled", "disabled");
                }
            } 
        });
        }
        </pre>
        you can find the fiddle in : https://jsfiddle.net/s8uv2gkp/
    
    0 讨论(0)
  • 2021-02-07 01:52

    By far the easiest, would be to rely on the HTML5 validation you're already using.

    You'd have to add required to all form controls if you want to require all of them, and that can easily be done by using jQuery's :input selector and setting the property, like so

    $(':input:not(#subnewtide)').prop('required', true)
    

    We'll exclude the submit button, as that doesn't have to be required, obviously, not that it would matter in this case.

    Then we'll listen for the input event, which covers all sorts of inputs, like typing, pasting etc, and the change event as well to cover the radio button.

    Using form.checkValidity() tells us if the form is valid, and returns a boolean, so we could use it directly to set the disabled property of the submit button.

    All together it looks like this, and that's all you need, a few lines of really simple code

    $(':input:not(#subnewtide)').prop('required', true).on('input change', function() {
        $('#subnewtide').prop( 'disabled', !this.form.checkValidity() );
    });
    

    FIDDLE

    If you have to support old browsers that don't have HTML5 validation, you can use the H5F polyfill

    0 讨论(0)
  • 2021-02-07 01:52

        var inputs = $("form#myForm input, form#myForm textarea");
    
        var validateInputs = function validateInputs(inputs) {
          var validForm = true;
          inputs.each(function(index) {
            var input = $(this);
            if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
              $("#subnewtide").attr("disabled", "disabled");
              validForm = false;
            }
          });
          return validForm;
        }
    
    
        inputs.each(function() {
          var input = $(this);
          if (input.type === "radio") {
            input.change(function() {
              if (validateInputs(inputs)) {
                $("#subnewtide").removeAttr("disabled");
              }
            });
          } else {
            input.keyup(function() {
              if (validateInputs(inputs)) {
                $("#subnewtide").removeAttr("disabled");
              }
            });
          }
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="#" method="post" id="myForm">
    
      Title:
      <input id="titlenewtide" type="text" name="title" required>
      <br>Description:
      <textarea name="description" id="description"></textarea>
      <br>Tag:
      <input id="newtag" type="text" name="newtag" required>
      <br>Category:
      <input type="radio" name="category" value="19" required>Animation
      <button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
    
    </form>

    0 讨论(0)
  • 2021-02-07 01:53

    My solution is base on standard JavaScript.

    HTML form

    <form action="#" method="post" id="new_tide" name="form1">
        Title: <input onkeyup="myBtnActivator(1)" id="titlenewtide" name="title" type="text" required> <br>
        Description: <textarea onkeyup="myBtnActivator(2)" id="description" name="description"></textarea> <br>
        Tag: <input id="newtag" onkeyup="myBtnActivator(3)" name="newtag" type="text" required> <br>
        Category: <input name="category" onchange="myBtnActivator(4)" type="radio" value="19" required> Animation
        <button id="subnewtide" name="subnewtide" type="submit" value="Submit">Submit</button>
    </form>
    

    JavaScript

    <script>
        document.getElementById("subnewtide").disabled = true;
        var input1 = false;
        var input2 = false;
        var input3 = false;
        var input4 = false;
    
        function myBtnActivator(i) {
            switch (i) {
                case 1:
                    input1 = true;
                    if (document.form1.title.value == "")
                        input1 = false;
                    break;
                case 2:
                    input2 = true;
                    if (document.form1.description.value == "")
                        input2 = false;
                    break;
                case 3:
                    input3 = true;
                    if (document.form1.newtag.value == "")
                        input3 = false;
                    break;
                case 4:
                    input4 = true;
                    if (document.form1.subnewtide.value == "")
                        input4 = false;
                    break;
            }
            trigger();
        }
    
        function trigger() {
            if (input1 == true && input2 == true && input3 == true && input4 == true) {
                document.getElementById("subnewtide").disabled = false;
            } else {
                document.getElementById("subnewtide").disabled = true;
            }
        }
    </script>
    
    0 讨论(0)
  • 2021-02-07 01:55

    Thought I might chip in. Assuming as little as possible.

    jQuery("input, textarea").on("keyup click", function () { // going vanilla after easy-mode attach
        var sub = document.getElementById('subnewtide');
        if (require_all(find_form(this))) {
            sub.removeAttribute('disabled');
            sub.disabled = false;
        } else {
            sub.setAttribute('disabled', 'disabled');
            sub.disabled = true;
        }
    });
    
    function concat(a, b) { // concating Array-likes produces Array
        var slice = [].slice; // not assuming Array.prototype access
        return [].concat.call(
            slice.call(a, 0),
            slice.call(b, 0)
        );
    }
    
    function find_form(e) { // shim input.form
        if (e) do {
            if (e.tagName === 'FORM') return e;
        } while (e = e.parentNode);
        return null;
    }
    
    function require_all(form, dontIgnoreHidden) { // looks at textareas & inputs (excluding buttons)
        var inp = concat(form.getElementsByTagName('input'), form.getElementsByTagName('textarea')),
            rad = {}, // not assuming Object.create
            i, j,
            has = {}.hasOwnProperty; // not assuming Object.prototype access
        for (i = 0; i < inp.length; ++i) {
            switch ((inp[i].type || '').toLowerCase()) {
                default: // treat unknown like texts
                case 'text':
                    if (!inp[i].value) return false; break;
                case 'checkbox':
                    if (!inp[i].checked) return false; break;
                case 'radio':
                    j = inp[i].getAttribute('name');
                    if (!rad[j]) rad[j] = inp[i].checked;
                    break;
                case 'hidden':
                    if (dontIgnoreHidden && !inp[i].value) return false; break;
                case 'button':
                case 'submit':
                    break;
            }
        }
        for (j in rad) if (!has || has.call(rad, j)) // not assuming hasOwnProperty
            if (!rad[j]) return false;
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题