开发者

Make javascript validation happen sooner on click?

So I have a form as such:

 <form action="URL" name=myform method=post onsubmit="return validateFormOnSubmit(this)" autocomplete=off>

When the form is submitted, it checks for validation.

Earlier though, I have code like this:

<script type="text/javascript">

  $(function() {
    $("#submitbutton").click(function() {

      var fname = $("input#first_name").val();
      var lname = $("input#last_name").val();
      var email = $("input#email").val();
      var leadsource = $("input#leadsource").val();
      var country = $("input#country").val();
      var phone = $("input#phone").val();
      var oid = $("input#oid").val();
      var retURL = $("input#retURL").val();
      var crazy
= $("input#00N40000001mCkP").val();
        var dataString = '&email=' + email + '&phone=' + phone + '&oid=' + oid +开发者_如何转开发 '&retURL=' + retURL + '&leadsource=' + leadsource + '&country=' + country;   //alert (dataString);return false;   $.ajax({
    type: "POST",
    url: "MYURL.php?first_name="
+ fname + "&last_name=" + lname,
    data: dataString, 
    success: function(response) { $(myform).submit(); }
    });
    return false;   });

  });   </script>

Essentially whats happening is, the form data is initially sent to a different url through an AJAX submit prior to completing the real form. On success of the ajax push - the form is submitted, and then the form is validated.

I need the form validation to have right when #submitbutton is clicked though - prior to the ajax request. Any ideas?


That code should work just fine. If you want to add it to a onclick= property on the element (I wouldn't, but if you insist), you can use this syntax to reference the form:

<input type="submit" onclick="return validateFormOnSubmit(this.parentNode)" />

And you'd have to do an e.preventDefault() and return false (maybe just one?) from the validateFormOnSubmit() function.


Take a look at preventDefault . Also, you can call validateFormOnSubmit in the anon function above and return false if it validation doesn't pass.


you should put some " " around your form tags attributes, and give it an id!

just call your validate function as the first line in your button click handler :)

 $("#submitbutton").click(function(e) {
   if( validateFormOnSubmit($('#myform'))){
       //do all the posting stuff

   }
   else{
      e.preventDefault();
      return false;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜