Reputation: 21
I had one form with inputs, chechbox, radio button, textarea. I would like to check with jquery if any of element of my form are filled, if at least one field is filled, then ok. Thanks
Upvotes: 2
Views: 5679
Reputation: 237865
You could try something like this:
if ($('input:checked, input[type="text"][value!=""], textarea[value!=""]) {
// some form field is filled
}
input:checked
looks for checked checkboxes or radio buttons, input[type="text"][value!=""]
looks for text input fields whose value is not an empty string, and textarea:not(:empty)
selects textareas that have some text within them (even if that's just whitespace). The selector selects all these elements and then .length
checks whether any elements were matched by these checks.
Upvotes: 3
Reputation: 1799
$("#form_id").submit(function() {
var filled = false;
$(this).find("input").each(function() {
if ($(this).val() != "") {
filled = true;
}
});
if (filled) { return true; }
else { // raise an error
return false; }
});
Essentially, just loop through the input fields and see if any are not empty. If the jQuery submit handler returns true, then the default behavior of the form occurs (it submits) and if it returns false, then nothing will happen.
Upvotes: 4