I got 4 input boxes in html and I want to check if one or many of them are empty. The issue with this code is the fact that at each new submit when the check fails I receive an incremental number of alerts. Meaning, if first time validation for Value2 fails I receive 1 alert, then I insert a correct Value2 but Value3 is wrong so instead to display only one alert for Value3 I receive a bunch of 2 alerts, and so on for each new submit…
<script>
function onSubmitNotification() {
var checkThisOnes = ["Value1", "Value2", "Value3", "Value4"];
$('#myform').submit(function() {
for (i = 0; i < checkThisOnes.length; i = i + 1) {
var checkedValue = $('#'+checkThisOnes[i]).val();
if (checkedValue === undefined || checkedValue === "") {
alert("This field is empty: " + checkThisOnes[i])
return false
}
}
});
</script>
2
Answers
use
event.preventDefault()
on submit. This will stop default submit behavior.I don’t know why you need to use
onSubmitNotification()
but without that also it will work .Also,remove return false and usee.preventDefault()
to avoid default submission.Demo Code :