checking if form inputs are empty with jquery
There are some o开发者_如何学Pythonther threads which ask this question, but I think I think I have a slightly different issue.
I am trying to make a form where the submit button initially is disabled, and when the form is complete the button will become enabled. After struggling for a while, I found a post which I modeled the following code:
$('input, textarea, select').blur(function()
{
if( !$(this).val() ) {
$('#submit').removeAttr('disabled');
}
});
I soon realized that this wasn't going to work because in this code, the "this" refers only to the input tag which you just left, not all of the input tags at once. How can I refer to all of the input, select, and textarea tags at once in order to check if ALL of them are not empty?
Also, the way I made my form was that not all of the input boxes showed up at once. Some inputs didn't apply to people who answered "no" to a certain question, so I used the jquery slide up and down to get rid of them etc. Initially those tags are not showing. Do I have to modify this jquery function for it to check if those inputs are empty as well?
Simply loop through all elements you want to check:
$('input, textarea, select').blur(function() {
var valid = true;
$('input, textarea, select').each(function() {
if (!$(this).is(':visible')) return true; // check if element is displayed
if( !$(this).val() ) {
valid = false;
return false; // form is not valid so no need to go any further
}
});
if (valid) {
$('#submit').removeAttr('disabled');
}
});
EDIT
Regarding to your hidden input fields.
Add an extra check to see if element is visible.
Please remember to also always check on the server side!
One way, which is quite graceful IMO, is using a custom pseudo selector that can be used to find empty elements. First of all, add it using:
$.expr[':'].novalue = function(a) { return $(a).val().length === 0; };
Than, when you need to test if all the inputs are non-empty (probably in $(':input').blur(...)
),
if ($(':input:novalue', form_element).length === 0) {
// All the inputs has a value
$('#submit').removeAttr('disabled');
} else {
// Some of the inputs are empty
}
(form_element being the... well, <form>
element)
$('input, textarea, select').blur(function(){
checkSubmit();
});
function checkSubmit() {
var $vals = $('input:not([type="submit"]), textarea, select');
var $total = $vals.size();
var $count = 0;
$vals.each(function(){
if(!$this).val()) {
$count++;
}
});
if ($total === $count) {
$('#submit').removeAttr('disabled');
}
}
Reading your edit as well, I think you will want to just go ahead and do a validation setup on submit instead of something like this, that will be potentially more difficult than just validating the fields. To answer your last question, though, yes, you would need to adjust the query (note my adjustment for the input[type="submit"]
).
精彩评论