2017-08-28 150 views
0

所有回覆和幫助非常感謝!javascript onsubmit無法正常工作

HTML:

<h1>CONTACT US</h1> 
<form action="submit.html" target="_blank" method="post" onsubmit="return validate();"> 
    <label for="name">NAME</label> 
    <input id="contact-name" name="name" placeholder="Please enter your name..." type="text"> 
    <label for="email">EMAIL</label> 
    <input id="contact-email" name="email" placeholder="Please enter your contact email..." type="text"> 
    <label for="email">MESSAGE</label> 
    <textarea id="contact-message" name="message" placeholder="Please enter your message.."></textarea> 
    <p></p> 
    <input type="submit" id="submit" value="SUBMIT MESSAGE"> 
</form> 

JAVASCRIPT:

function validate() { 
    var username = document.getElementById("contact-name").value; 
    var email = document.getElementById("contact-email").value; 

    if (username==="" || email==="") { 
     alert("Please can you fill in all fields"); 
     return false; 
    } else { 
     return true; 
    } 
}; 
+3

發生什麼事,你有什麼要發生? –

+0

我想確保用戶填寫字段。如果他們沒有,並且他們提交了,我想要出現一條警告消息:「請填寫所有字段」。相反,當他們點擊提交而沒有填寫時,它不會帶來警報。它將它們發送到「感謝您的評論」提交頁面。 – CoderAz

+0

我能夠獲得兩個輸入字段的驗證註釋,並且它也限制從上面的代碼提交頁面。你還想要什麼呢? –

回答

0

你確定引入包含你的Javascript到HTML文件?請看下圖:

function validate() { 
 
    var username = document.getElementById("contact-name").value; 
 
    var email = document.getElementById("contact-email").value; 
 

 
    if (username==="" || email==="") { 
 
     alert("Please can you fill in all fields"); 
 
     return false; 
 
    } else { 
 
     return true; 
 
    } 
 
}
<html> 
 

 
<head> 
 
</head> 
 

 
<body> 
 
    <h1>CONTACT US</h1> 
 
    <form action="submit.html" target="_blank" method="post" onsubmit="return validate();"> 
 
    <label for="name">NAME</label> 
 
    <input id="contact-name" name="name" placeholder="Please enter your name..." type="text"> 
 
    <label for="email">EMAIL</label> 
 
    <input id="contact-email" name="email" placeholder="Please enter your contact email..." type="text"> 
 
    <label for="email">MESSAGE</label> 
 
    <textarea id="contact-message" name="message" placeholder="Please enter your message.."></textarea> 
 
    <p></p> 
 
    <input type="submit" id="submit" value="SUBMIT MESSAGE"> 
 
    </form> 
 
    <script src="script.js"></script> 
 
</body> 
 

 
</html>

+0

' – Howie