Stop Enter/Return key submitting a form
forms, javascript, jquery, jquery-events, keyboard-events
Solution
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;
});
Problem
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> ```