简体   繁体   中英

re-enable an input after it was disabled through javascript because it was empty

I am using jQuery Validator to validate a form and I wanted to disable the fields that were blank when the user clicks submit so that the server does not receive any data from the inputs that were left blank. To disable them, I used the following Javascript:

$(function() {
    $("#form1").submit(function() {
       $(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled");
  return true; // ensure form still submits
    });
});

Here is my problem: This code works great assuming the form was validated on the first submission. However, if the user hits submit but it was not validated, all of the alerts for various required fields and such pop-up, but all of the inputs are disabled. How can I fix this? I need to know how to re-enable them if the form is not validated and properly submitted.

It doesn't make sense to disable the field to submit. Rather—you should first do a front-end only validation that prevents submitting if there are empty fields (and those fields are required to not be empty).

You can set up a variable (or a function) to run through your validation and only submit if it returns true. This is a condensed example of just one input.

var validate = ($('input').val() == '') ? false : true;

if(validate){ 
    // submit your form
} else {
   // throw your errors
}

Then it would be good to clear your errors at the beginning of your validation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM