1

I want to stay on the current page, if the "Name" input field is empty. Right now, it shows the error message, and when you click ok, it still goes to the next page (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>

Jean
  • 313
  • 2
  • 5
  • 16

3 Answers3

1

try like so, returning your function at submit event of the form element

<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>
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

Misssing return keyword:

<input type="submit" 
onclick="return notEmpty(document.getElementById('Name'), 'Please enter your name')"   
name="submit" value="Send your message">
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • just to point out that this will work when the button has been clicked and not when the form is submitted... so if a user press "enter" when the focus is on the last field, he will submit the form *without* clicking the submit button. :) – Fabrizio Calderan Jun 22 '12 at 08:43
1

As you use HTML5 anyway, you might want to use the required attribute: http://www.w3schools.com/html5/att_input_required.asp

<form>
  <input id="message" required>
  <input type="submit" value="Submit">
</form>
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
asotbb
  • 119
  • 1
  • 9
  • Yeah, but this is useless, as it wont work in older browsers. Actually I'd like to remove that from appearing on my Email input fiel. I'm aware it's not set. But it magically appears nevertheless. – Jean Jun 22 '12 at 09:13
  • Well, I see your point, however it is a valid option or rather a valid extension to yours, because your JavaScript solution won't work for people having JavaScript turned off. – asotbb Jun 22 '12 at 17:23
  • Note: Both won't work for those having JavaScript turned off and not having a HTML5 Browser. So you'll need server-side validation, anyway. Concerning your problem, maybe this helps: http://stackoverflow.com/a/3092801 or you can turn off form validation with "nonvalidate='nonvalidate'", because at least I can leave it empty, but if I enter something it must be a valid mail adress. – asotbb Jun 22 '12 at 17:39