I have a table within a form. The table contains some form fields, but there are form fields outside of the table (but still within the form) too.
I know that Enter and Return are traditionally used to submit a form via the keyboard, but I want to stop this behaviour for fields within the table. For example, if I focus a field within the table and hit Enter/Return, nothing happens. If I focus a field outside of the table (but still within the form) then for it to submit as normal.
I have a jQuery plugin that targets this table. Simplified, this is what I've tried this far:
base.on('keydown', function(e) {
if (e.keyCode == 13) {
e.stopPropagation();
return false;
}
});
Where base
is the table jQuery object. This is within my plugin's init
method. However, hitting Enter still submits the form.
Where am I going wrong?
EDIT: Some simplified HTML:
<form method="" action="">
<input type="text" /><!--this should still submit on Enter-->
<table>
<tbody>
<tr>
<td>
<input type="text" /><!--this should NOT submit on Enter-->
</td>
</tr>
</tbody>
</table>
</form>
The disabled property was first introduced by Microsoft but has since been adopted as a standard by the W3C. So when the form is submitted - either by clicking on the submit button or pressing Enter in a text input field - the submit button will be disabled to prevent double-clicking.
addEventListener("submit",function(e){e. preventDefault(); return false;}); This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.
As someone already mentioned, if you switch the form to a post method and switch the Servlet to a doPost, you won't have this issue anymore. You can check if the user clicked the back button, disable form if true. Another way is by storing a cookie which you check on page load, if it exists you can disable the form.
Keycode 13 is the Enter key.
base.keypress(function(e) {
var code = e.keyCode || e.which;
if(code == 13)
return false;
});
or for only inputs:
$(':input', base).keypress(function(e) {
var code = e.keyCode || e.which;
if(code == 13)
return false;
});
I'm going to guess that a form element will fire the submit event, it doesn't bubble up through the table and on to the form, try this instread:
$('input, select, textarea', base).on('keydown', function(e) {
if (e.keyCode == 13) {
return false;
}
});
Note we're also providing context to the selector, so this keyDown
will only occur on elements (modify as required) within your table.
As gordan said in another comment, return false does both .preventDefault()
and .stopPropagation()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With