3

html:

<form id="form" action="/" method='post'>
<button>Button</button>
<input type="text">
<input type="submit" id="send-form" value="Send">
</form>

js:

$('#form').submit(function() {
    console.log('send');
    return false;
});

Why when I press the Button, the form is submitted (I need this element for another action)? How to prevent this?

vlad
  • 815
  • 2
  • 11
  • 25

4 Answers4

11

The default action for <button> is to be a submit button, but you can have it just be a "normal button" by doing the following:

<button type="button">Button</button>

See the HTML specs for more info.

Wogan
  • 70,277
  • 5
  • 35
  • 35
5

Try to add an onclick listener:

<button onclick="return false;">Button</button>

That should prevent that the button to submit the form. The click action is, with that trick, canceled.

rekire
  • 47,260
  • 30
  • 167
  • 264
  • 2
    For even more info, http://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms – dbd Mar 12 '12 at 08:11
2

It's failing for browsers that do not have console object - IE for example.

Just wrap it with try..catch and it will work for all browsers:

$('#form').submit(function() {
    try {
        console.log('send');
    }
    catch (e) {
    }

    return false;
});​

Live test case.

Edit: better yet, you can write your own function to show the message even for browsers without console:

function Log(msg) {
    if (typeof console != "undefined" && console.log) {
        console.log(msg);
    } else {
        var myConsole = $("MyConsole");
        if (myConsole.length == 0) {
            myConsole = $("<div></div>").attr("id", "MyConsole");
            $("body").append(myConsole);
        }
        myConsole.append(msg + "<br />");
    }
}

$('#form').submit(function() {
    Log('send');

    return false;
});

This will append the message to the document itself when console is not available. Updated fiddle.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
2
<form id="form" action="/" method='post'>
<input type="button" value="Button">
<input type="text">
<input type="submit" id="send-form" value="Send">
</form>​

This will create "not-submitting" button. Example: http://jsfiddle.net/R3UrK/1/

Kedor
  • 1,488
  • 5
  • 29
  • 53