I've been looking around for a solution to this, but can't seem to find any examples that work for me. Here's what I've got so far:
$("#register-form").submit(function(){
if($(".required input").val() == '') {
alert("Please fill in all the required fields (indicated by *)");
$(".required").addClass('highlight');
// $('input[type=submit]', this).attr('disabled', 'disabled');
return false;
}
});
For some reason, when I submit the form with none of the required fields filled in (there are two), then it works, but if one of them is filled out, it doesn't.
Any ideas why?
Thanks
osu
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.
To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.
The problem with your code is that you're only testing the first field you've got flagged as required. $(".required input")
only returns the first input in your form that matches that selector.
This loops through all the inputs in the form that are flagged required (according to your selector). If it finds one with a value of '' then it sets the submit function to return false and highlights the blank fields. It also removes the highlight class from fields that are now valid but were previously invalid in an early form submit attempt.
$("#register-form").submit(function(){
var isFormValid = true;
$(".required input").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("highlight");
isFormValid = false;
}
else{
$(this).removeClass("highlight");
}
});
if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");
return isFormValid;
});
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