I need to validate a form with jQuery. I can check all my inputs one by one, but it's not a very practical solution.
How can i check if all my inputs are non-empty more efficiently? In my form i can have input
elements of different types: text, several groups of radio, select etc.
To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.
click(function(e) { var isValid = true; $('input[type="text"]'). each(function() { if ($. trim($(this). val()) == '') { isValid = false; $(this).
Just use:
$("input:empty").length == 0;
If it's zero, none are empty.
To be a bit smarter though and also filter out items with just spaces in, you could do:
$("input").filter(function () { return $.trim($(this).val()).length == 0 }).length == 0;
Use each
:
var isValid; $("input").each(function() { var element = $(this); if (element.val() == "") { isValid = false; } });
However you probably will be better off using something like jQuery validate
which IMO is cleaner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With