I want to show a warning message if user does not complete entire form but it seems not to work as I want. The jQuery .each method only collects data from the first input field. If I leave the first field empty it works correctly but if I fill only the first field and leave other fields empty it shows success which is wrong.
// send message on click
$("#submit").click(function() {
// store values
var data = $("#form").serialize();
$(":input, textarea").each(function() {
// if empty show warning
if ( $(this).val() === "" ) {
$(".message-fail").fadeIn(500);
}
// if not empty send message
else if ( !$(this).val() ) {
$.ajax({
type: "POST",
url: "mail.php",
data: data,
success: function() {
$(".message-sent").fadeIn(500);
}
});
}
});
});
You can do following process:
BUT I THINK YOU DON’T NEED AJAX FOR EVERY FIELD
Explanation:
$.trim(this.value)-> check for value existsor can also use (first one is better)
$.trim($(this).val()).length-> checks for value exists