<div>
<p>Form 1, default enter behavior, when there is only a textbox, and there is a submit button</p>
<p>If you press enter, it's submitted</p>
<form method="GET" id="form1">
<input type="text" />
<input type="submit" />
</form>
</div>
<div>
<p>Form 2: prevents default behavior on textbox</p>
<p>If you press enter the form is not submitted</p>
<form method="GET" id="form2">
<input type="text" />
<input type="submit" />
</form>
</div>
<div>
<p>Form 3: submit shuld only happen if there is only one textbox, but it depends on the browser</p>
<p>If you press enter the form should not be submitted, because there are several textboxes, but I bet it will be submitted</p>
<form method="GET" id="form3">
<input type="text" />
<input type="text" />
<input type="submit" />
</form>
</div>
// This suppres the default behavior of submitting the
// form when the enter key is pressed in the textbox
$('#form2').on('keypress', function (e) {
if (e.which === 13) {
e.preventDefault();
console.log('key press 13');
}
});
// This event is triggered when any form is submitted
// (but doesn't send it, becasue of prevent default).
$('form').on('submit', function(e) {
console.log('Sending form', e.target.name);
e.preventDefault();
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.