wdphd
wdphd

Reputation: 915

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. But whenever user clicks on submit button, the page seems to be submitting automatically. I have used jquery's preventDefault and stopPropogation too. But its still not working. I'm new to jQuery and I might be missing something small. 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.

Upvotes: 1

Views: 12632

Answers (4)

Sergio
Sergio

Reputation: 28837

jQuery needs a # to identify id and . for class.

If you do not want to submit the form use this:

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

    alert("not submited");
    return false;

    });

Upvotes: 3

user2548000
user2548000

Reputation: 1

Sergio is right.

Also, the click listenter will never work on the input either, the right selector is

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

Upvotes: 0

Adam
Adam

Reputation: 802

There's a couple things you can take a look at. First, change from type="submit" to 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. You can just set the returnValue to false.

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

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

What you actually want is to capture the submit(), and preventDefault() on that.

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

Upvotes: 5

Related Questions