Imagine a simple form with method POST
and 30 inputs.
I would like to create a jQuery function that will be called from submit button. I searched about how to check all inputs that are required, but didn't find anything to help.
I would like something like this:
var inputs_required = all inputs from my form which have attribute required;
function check_required_inputs() {
if(inputs_required != "") {
//create ajax with serialize() and submit form;
}
} else {
//highlight inputs that are empty and show a message;
}
Can this be achieved in jQuery?
Just use: $("input:empty"). length == 0; If it's zero, none are empty.
$('#dynamic-form-fields input:required'). each(function() { if ($(this). val() === '') alert('error please fill all fields! '); });
each(function() { if ($(this). val() != "") { empty = false; return false; } }); This should look all the input and set the empty var to false, if at least one is not empty.
Zakaria already posted an answer, which should work great. Alternatively, instead of having a custom class, you could instead find all input
, textarea
and select
elements that have the attribute required
and are visible
using
var required = $('input,textarea,select').filter('[required]:visible');
And then iterate through them using each()
etc.
Example:
var allRequired = true;
required.each(function(){
if($(this).val() == ''){
allRequired = false;
}
});
if(!allRequired){
//DO SOMETHING HERE... POPUP AN ERROR MESSAGE, ALERT , ETC.
}
You could give all your required inputs a common class (required
for example) then use each()
to loop through them like :
function check_required_inputs() {
$('.required').each(function(){
if( $(this).val() == "" ){
alert('Please fill all the fields');
return false;
}
});
return true;
}
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