2012-06-22 36 views
1

如果「名稱」輸入字段爲空,我想保留在當前頁面上。 現在,它顯示錯誤消息,並且當您單擊確定時,它仍會轉到下一頁(contactcaptcha.php)。當表單驗證爲false時,保持當前頁面

function notEmpty(elem, helperMsg){ 
if(elem.value.length == 0){ 
    alert(helperMsg); 
    elem.focus(); 
    return false; 

} 
return true; 
} 




<form id="action" action="contactcaptcha.php" method="post"> 
    <fieldset> 

     <textarea id="message" name="Message" placeholder="What's on your mind?"></textarea> 

     <input id="Name" name="Name" placeholder="Enter your full name" type="text"> 

     <input id="Email" name="Email" placeholder="Enter your email address" type="email"> 

     <input type="submit" onclick="notEmpty(document.getElementById('Name'), 'Please enter your name')" name="submit" value="Send your message"> 

    </fieldset> 

回答

1

嘗試像這樣,在submit事件form元素的返回你的函數

<form id="action" action="contactcaptcha.php" method="post" 
onsubmit="return notEmpty(document.getElementById('Name'), 'Please enter your name')"> 
    <fieldset> 
    ... 
    <input type="submit" name="submit" value="Send your message">  
    </fieldset> 
</form> 
1

Misssing return關鍵字:

<input type="submit" 
onclick="return notEmpty(document.getElementById('Name'), 'Please enter your name')" 
name="submit" value="Send your message"> 
+0

只是想指出的是,當按鈕被點擊,這將不工作,當表單提交...因此,如果用戶按「確認」時,重點是最後一個字段,他將提交表格*,不需要點擊提交按鈕。 :) – fcalderan

1

當您使用HTML5反正你可能想要使用required attributehttp://www.w3schools.com/html5/att_input_required.asp

<form> 
    <input id="message" required> 
    <input type="submit" value="Submit"> 
</form> 
+0

是的,但這是無用的,因爲它不適用於舊版瀏覽器。其實我想從我的電子郵件輸入欄中刪除它。我知道它沒有設置。但它奇蹟般地出現。 – Jean

+0

嗯,我明白了你的觀點,然而這是一個有效的選擇,或者說是對你的擴展,因爲你的JavaScript解決方案不適用於JavaScript關閉的人。 – asotbb

+0

注意:這兩種方法對於JavaScript關閉且沒有HTML5瀏覽器的用戶都無效。無論如何,你需要服務器端驗證。關於你的問題,也許這有助於:http://stackoverflow.com/a/3092801,或者你可以關閉表單驗證與「nonvalidate ='nonvalidate'」,因爲至少我可以留空,但如果我輸入的東西它必須是有效的郵件地址。 – asotbb

相關問題