cannotcompute
cannotcompute

Reputation: 397

event.preventDefault() and return false; are failing me

I think I am just too tired right now but why is this not working? Got a simple form with id="contact"

   $("#contact").on('submit', function(event) {
       event.preventDefault();

       var name = $('#name').serialize();
       var email = $('#email').serialize();
       var message = $('#message').serialize();
       alert(name);

        }); 
    });

(I stripped out the AJAX that follows) Why isnt' the window prevented from refreshing? return false; didnt do anything either.. I am probably missing something obvious here

Upvotes: 1

Views: 232

Answers (2)

castarco
castarco

Reputation: 1376

The first point:

  • You should use .val() instead of serialize() .
  • .serialize() is a method applicable to the element, this method returns a string like this : field1=value1&field2=value2&...&fieldn=valuen

An example:

$("#contact").submit(function(event) {
    event.preventDefault();
    var name = $('#name').val(),
        email = $('#email').val(),
        message = $('#message').val();

    alert(name);
    return false; // "Defensive" line (i think it's not necessary)
});

I hope it will help!

Upvotes: 0

insomiac
insomiac

Reputation: 5664

You can try this :

$(document).on('submit', "#contact", function(event) {
   event.preventDefault();

   var name = $('#name').serialize();
   var email = $('#email').serialize();
   var message = $('#message').serialize();
   alert(name);
   return true; 
});

Upvotes: 1

Related Questions