Force user to fill all fields before enabling form

2020-05-30 06:56发布

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, I'm able to force the title field to have content before submit button is enabled. How do I make it so that all other fields need to be filled too before submit button is enabled.

    jQuery("input[type='text']").on("keyup", function () {
        if (jQuery(this).val() != "" ) {
            if (jQuery("#titlenewtide").val() != '')
            {
                jQuery("#subnewtide").removeAttr("disabled");
            }
        } else {
            jQuery("#subnewtide").attr("disabled", "disabled");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
        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>

Note that I am loading the JavaScripts in my footer.

12条回答
聊天终结者
2楼-- · 2020-05-30 07:10

    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>

查看更多
Melony?
3楼-- · 2020-05-30 07:18

Try utilizing .siblings() , .map() to compile values of form elements , Array.prototype.every() to return Boolean representation of input , textarea values , set disabled property of form input[type=submit] element

$("form *[required]").on("input change", function(e) {
  $(this).siblings("[type=submit]").prop("disabled"
  , !$(this).siblings(":not([type=submit])").add(this).map(function(_, el) {
    return el.type === "radio" ? el.checked : el.value
   }).get().every(Boolean)
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form action="#" method="post" id="new_tide">
    Title: <input id="titlenewtide" type="text" name="title" required> <br>
    Description: <textarea name="description" id="description" required></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>

查看更多
做个烂人
4楼-- · 2020-05-30 07:20
  • 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>

查看更多
Root(大扎)
5楼-- · 2020-05-30 07:20

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>
查看更多
Animai°情兽
6楼-- · 2020-05-30 07:21

Use this code below. On each input, it will check all the form fields by using this function validate().

jQuery("input[type='text'], textarea").on("input", function () {
    var isValid = validate();
    if (isValid) {
      jQuery("#subnewtide").removeAttr("disabled");
    } else {
        jQuery("#subnewtide").attr("disabled", "disabled");
    }
});


function validate() {
  var isValid = true;
  $('input, textarea').each(function() {
    if ($(this).val() === '')
        isValid = false;
  });
  return isValid;
}

Fiddle

Update

To make it validate if the form has id="new_tide" and fix about the radio button.

$("input[type='text'], textarea").on("change input", function() {
  validate($(this));
});

$("input:radio[name='category']").on("change", function() {
    validate($(this));
});

function validate(self) {
  if (self.parents("form:first").attr("id") == "new_tide") {
    var isValid = true;
    $('input[type="text"], textarea').each(function() {
      if ($(this).val() === '')
        isValid = false;
    });

    if (!$("input:radio[name='category']").is(':checked'))
      isValid = false;

    if (isValid) {
      $("#subnewtide").removeAttr("disabled");
    } else {
      $("#subnewtide").attr("disabled", "disabled");
    }
  }
}

Fiddle

查看更多
一纸荒年 Trace。
7楼-- · 2020-05-30 07:23

Here is a quick way to accomplish that. It involves attaching a change event listener to :radio and :checkbox elements and an input event listener to other elements. These can both use a common predefined handler that will count the number of unfilled element each time each of these events fires on the appropriate element.

function checkForm() {
    //define and initialize variables
    var unfilled = 0,
        form = $(this.form);

    //disable submit button if enabled
    $(':submit', form).prop('disabled', true);

    //count number of unfilled elements
    $(':input', form).each(function() {
        if( $(this).is(':radio,:checkbox') ) {
            $('input[name=' + this.name + ']:checked').length || unfilled++;
        } else {
            $('[name=' + this.name + ']').val() || unfilled++;
        }
    });
  
    //enable submit button if no unfilled element is found
    unfilled || $(':submit', form).prop('disabled', false);
}

//set up event listeners to fire above handler
$(':text,textarea,select').on('input', checkForm);
$(':radio,:checkbox').on('change', checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
    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>

查看更多
登录 后发表回答