保持当前页面上,当表单验证是假的(Stay on current page, when form v

2019-07-30 01:32发布

我想留在当前页面上,如果“名称”输入字段为空。 现在,它显示错误消息,当您单击确定,但它仍然进入下一个页面(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>

Answer 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>


Answer 2:

Misssing return关键字:

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


Answer 3:

当您使用HTML5,无论如何,你可能想使用要求的属性 : http://www.w3schools.com/html5/att_input_required.asp

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


文章来源: Stay on current page, when form validation is false