10

I got a button:

Whenever I click on it, it submits to a form.

I want to hijack this behavior, so when I click, it calls a JS function instead. How do I do this? I added:

$('input.submit').live('click', addFood);

The problem is it still submits to the form. When I remove "type="submit", it works.

I don't want to remove the HTML code. it'a also bound to CSS, and I don't want to change CSS because I'm afraid of messing it up =)

So question is: how do to change behavior of submit button so it doesn't submit to form but calls my Javascript (JQuery) function?

2
  • 1
    Oops, I just realized I needed a "return false" in my addFoods function, otherwise it calls the function AND submits it to the form. Problem solved! Off to bed =)
    – Henley
    Oct 16, 2011 at 4:28
  • 2
    Hisoka: it's ok to answer your own question. Oct 16, 2011 at 4:38

2 Answers 2

17

Target the form instead, not the submit button

$("form").submit(function(e) {

    e.preventDefault();
    e.returnValue = false;

    // do things
});
1
  • 3
    This solution was deprecated in Jquery 1.7
    – cromanelli
    Mar 8, 2014 at 11:37
13

Just for the sake of keeping this answer updated change :

$("form").live('submit', function(e) {

    e.preventDefault();
    e.returnValue = false;

    // do things
});

with :

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

    e.preventDefault();
    e.returnValue = false;

    // do things
});

$(selector).live() was deprecated in Jquery 1.7 and removed from the framework in Jquery 1.9.

Here´s the documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.