开发者

Jquery stop form submission on same page

开发者 https://www.devze.com 2023-02-01 19:34 出处:网络
I have a form within a php page. And I want to stop it\'s submission with jquery for vali开发者_高级运维dation purposes.

I have a form within a php page. And I want to stop it's submission with jquery for vali开发者_高级运维dation purposes.

$('form').submit(function(){
        alert('submitting');
        return false;
    });

Now this works just fine, if I try to send the form to another page. But if I write the php side validation and insertion codes on the same page as the form (with form's action=""), the page refreshes on submit and the data gets inserted in db.....any way to stop this? or do I have to use two separate pages for form and serverside validation/insertion ?


I don't know how much it could help, but for validation I use to hook an handler on the submit button instead of the form's submit event.

I mean that if you have in your HTML:

<form action="" method="POST">
...
   <input type="submit" id="submit-button" />
</form>

on your javascript you will have:

$("#submit-button").click(function(e) {
   if (!valid()) { // you have a method that performs validation
      e.preventDefault(); // calling preventDefault is better than "return false"
   }
}

Hope this helps.

0

精彩评论

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

关注公众号