2011-01-22 137 views
4

我正在做一個窗體的簡單驗證。 JavaScript驗證工作正常,彈出警告框出現正確的錯誤,但點擊「確定」後,我會重新定向到下一頁。理想情況下,它應該保持在同一頁面上,以便用戶可以修改他/她的錯誤。請儘快幫助,這是一個學校項目,截止日期爲3天! 。:(在此先感謝JavaScript提醒錯誤消息

<script type = "text/javascript"> 

function show_alert() { 
    if (document.getElementById('time1').value == document.getElementById('time2').value) alert("ERROR! You cannot book the same timing twice!") 
    else if (document.getElementById('time1').value == document.getElementById('time3').value) alert("ERROR! You cannot book the same timing twice!") 
    else if (document.getElementById('time1').value == document.getElementById('time4').value) alert("ERROR! You cannot book the same timing twice!") 
    else if (document.getElementById('time1').value == "0") alert("ERROR! You cannot leave the first time slot blank!") 
    else {} 
} 
</script> 

回答

3

這應該是很容易解決您的窗體標籤的方法的onsubmit,這樣做:

<form onsumbit="return show_alert();"> 

而不是

<form onsumbit="show_alert();"> 

沒有return部分,腳本將運行,並且表單將以任何方式提交。另外,如果腳本中存在錯誤情況,則需要添加return false;否則表單仍將提交,並且01如果沒有錯誤,則爲。您可以編輯腳本,如下所示:

<script type = "text/javascript"> 

function show_alert() { 
    if (document.getElementById('time1').value == document.getElementById('time2').value) { 
     alert("ERROR! You cannot book the same timing twice!"); 
     return false; 
    } else if (document.getElementById('time1').value == document.getElementById('time3').value) { 
     alert("ERROR! You cannot book the same timing twice!"); 
     return false; 
    } else if (document.getElementById('time1').value == document.getElementById('time4').value) { 
     alert("ERROR! You cannot book the same timing twice!"); 
     return false; 
    } else if (document.getElementById('time1').value == "0") { 
     alert("ERROR! You cannot leave the first time slot blank!"); 
     return false; 
    } else { 
     return true; 
    } 
} 

</script> 
+0

此外,`show_alert`需要返回true或false,指示是否應提交表單。 – casablanca 2011-01-22 17:27:25