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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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/

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.