我有一個for
循環,通過class="required"
通過每個輸入,它的空它改變了它的背景色。此外,它還向頁面的一部分添加了一條消息:「需要紅色背景色的字段」。但是,我只希望消息顯示一次。即使5個字段爲空,也只應顯示一條消息。有什麼建議麼?只運行一次?
繼承人我的代碼:
<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>
是jQuery的一個選項? – asawyer
@Asawyer不,對不起... –