如果“名称”输入字段为空,我想留在当前页面上。 现在,它显示错误消息,当您单击确定时,它仍然会转到下一页(contactcaptcha.php)。
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>
答案 0 :(得分: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 :(得分:1)
误导return
关键字:
<input type="submit"
onclick="return notEmpty(document.getElementById('Name'), 'Please enter your name')"
name="submit" value="Send your message">
答案 2 :(得分:1)
当您使用HTML5时,您可能想要使用required attribute:http://www.w3schools.com/html5/att_input_required.asp
<form>
<input id="message" required>
<input type="submit" value="Submit">
</form>