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\")
$("#register-form").submit(function() {
$('.required input').each(function() {
if ($($this).val() == '') {
$(this).addClass('highlight');
}
});
if ($('.required input').hasClass('highlight')) {
alert("Please fill in all the required fields (indicated by *)");
return false;
}
}
Give that a shot.
EDIT Moved the alert so users don't get their faces blown off with alert messages, good catch.
Maybe your condition should be this:
if($("input.required").val() == '')... //Pay attention to the selector
Cause your selector was finding all inputs children of .required
If the
$(".required input")
is matching more than one element, then
$(".required input").val() == ''
probably won't do what you're expecting.
This code get all form fields with select list & checkbox etc.
var save_prms = $("form").serializeArray();
$(save_prms).each(function( index, element ) {
alert(element.name);
alert(element.val);
});
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;
});
name of the input or id in this case used id of the input
HTML:
<input type="text" id="id"... />
JQUERY:
if (!$("#id").val()) {
do something...
}