I have a for loop that goes through each input with class="required" , and it its empty it changes its background color. Also, it adds a message to part of the page: “Fields with red background color are required”. But, I only want the message to be displayed once. Even if 5 fields are empty, only one message should be displayed. Any suggestions?
Heres my code:
<script type="text/javascript" >
window.onload = function() {
document.getElementById("formID").onsubmit = function() {
var fields = this.getElementsByClassName("validate"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ffb8b8";
var inst = document.getElementById('inst');
var reason = inst.insertRow(-1);
var cell1=reason.insertCell(0);
cell1.innerHTML = '<p>Fields with a red background are required and empty. Please fill them in and try resubmitting. Thanks.</p>';
inst.appendChild(reason);
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
</script>
Well this should be rather simple – you’ve already got a boolean variable to say whether the validation has failed –
sendForm. So just take the “append message” part out of the loop and into the if.