Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to hijack input type=submit on click behavior?

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?

like image 867
Henley Avatar asked Oct 16 '11 04:10

Henley


2 Answers

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

like image 185
cromanelli Avatar answered Oct 14 '22 00:10

cromanelli


Target the form instead, not the submit button

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

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

    // do things
});
like image 23
Steve Robbins Avatar answered Oct 14 '22 00:10

Steve Robbins