简体   繁体   English

表单提交-防止页面重新加载jQuery

[英]Form Submit - Preventing page reload jQuery

I'm building a contact form and i want to submit the data through ajax and display the result back via the same. 我正在建立联系表单,我想通过ajax提交数据并通过相同的方式显示结果。 But whenever user clicks on submit button, the page seems to be submitting automatically. 但是,每当用户单击“提交”按钮时,页面似乎就会自动提交。 I have used jquery's preventDefault and stopPropogation too. 我也使用了jQuery的preventDefaultstopPropogation But its still not working. 但是它仍然无法正常工作。 I'm new to jQuery and I might be missing something small. 我是jQuery新手,可能缺少一些小东西。 Here's the code: 这是代码:

Form 形成

<form action="#" method="post" accept-charset="utf-8" name="contactform" id="contactform">
        <p>Name<br/><input type="text" name="cname" value="" id="cname" required /></p><br/>
        <p>Email<br/><input type="email" name="cemail" value="" id="cemail" required /></p><br/>
        <p>Message<br/><textarea name="cmessage" cols="40" rows="10" id="cmessage" required ></textarea></p>

        //Re-captcha code here
        <p><input type="submit" name="contact_submit" value="Submit" id="contact_submit"  /></p>
        </form> 

        <br />
        <div id="result"></div>

Script 脚本

$(document).ready( function(){
$("#contact_submit").click( function(e){

   e.preventDefault();
   e.stopPropagation();




 });

 $("#result").html('');

 $("#contactform").validate();


 });

I have included jQuery Validation Plugin which also isn't working. 我包含了jQuery Validation插件,该插件也无法正常工作。

What you actually want is to capture the submit() , and preventDefault() on that. 你真正需要的是捕捉submit()preventDefault()上。

$('#contactform').submit(function(e){
    e.preventDefault();
});

jQuery needs a # to identify id and . jQuery需要一个#来标识id和. for class. 上课。

If you do not want to submit the form use this: 如果您不想提交表单,请使用以下命令:

$("#contactform").on('submit', function(e){

    alert("not submited");
    return false;

    });

There's a couple things you can take a look at. 您可以看几件事。 First, change from type="submit" to type="button". 首先,从type =“ submit”更改为type =“ button”。 That gives you all the same functionality without the submit. 这为您提供了所有相同的功能,而无需提交。 Second, if you're trying to get this to work in IE, it's not working because IE doesn't have the preventDefault method on the event object. 其次,如果您试图使它在IE中工作,那么它将无法正常工作,因为IE在事件对象上没有preventDefault方法。 You can just set the returnValue to false. 您可以将returnValue设置为false。

$("#contactform").submit( function(e){
   e.stopPropagation();
   if(e.preventDefault){
      e.preventDefault();
   }else{
      e.returnValue = false;
   }
});

Sergio is right. 塞尔吉奥是正确的。

Also, the click listenter will never work on the input either, the right selector is 此外,点击监听器也永远不会在输入上起作用,右侧的选择器是

$('input[name="contact_submit"]')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM