Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery error submit form validation

Tags:

jquery

forms

I need to validate input using JavaScript and jQuery when someone submit my newsletter form

for some reason it does not work. it submit the form without alerting any errors

Here's what i have so far:

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  <script type="text/javascript">

  $(document).ready(function(){
  function go() {
      if($('#name').val() == '') {
          alert('error: name is required');
      }
      $('form').submit();
  }
  });


  </script>
  </head>

  <form method="post" action="">
    Name *<input type="text" name="name" id="name"/>
    E-Mail *<input type="text" name="email" id="email"/>

    <input class="submit" type="submit" value="Submit" name="submit" id="submit" onclick="go();">
  </form>

Why I don't see the alert when I don't put anything in the name and then submit the form?

like image 209
Kevin Kelly Avatar asked Jan 03 '12 01:01

Kevin Kelly


1 Answers

Rather than using onclick on the submit button, use onsubmit="return go(); on the form element. Or, use jQuery $('form').submit(function(){ ... });

And, once you encounter an error, you need to return false from the function to prevent it from executing any further.

like image 156
dakdad Avatar answered Oct 03 '22 15:10

dakdad