I'm trying to validate a form with jQuery.
I'm looping all inputs in a table with each()
. When clicking the save button, if one input is empty, simply the input should change border color to red. If all inputs are not empty, then the panel should animate and the alert message should show. But for some reason, if you leave any of the inputs empty, both conditions (if and else) happen. Please refer to jsfiddle.
Other similar posts like mine are fixed by adding return false to exit the each loop as soon as the if statement is met, but it doesn't work for me. Can you please help me understand what I'm doing wrong? Thank you!
https://jsfiddle.net/KlaytonJames/rvh9Lwn0/5/
$(document).ready(function() {
$("button.edit").on("click", function() {
$(this).parents(".panel").addClass("rotate");
$(this).parents("tr").addClass("editable");
})
$("button.save").on("click", function() {
$("table input").each(function() {
var ret = true;
if ($(this).val() == '') {
$(this).addClass("error");
ret = false;
return false;
} else {
$(this).removeClass("error").parents(".panel").removeClass("rotate");
$("table tr").removeClass("editable");
$(".alertbox").addClass("show");
}
return ret;
});
})
})
Aucun commentaire:
Enregistrer un commentaire