I have a survey on a website, and there seems to be some issues with the users hitting enter (I don\'t know why) and accidentally submitting the survey (form) without clicki
Not putting a submit button could do. Just put a script to the input (type=button) or add eventListener if you want it to submit the data in the form.
Rather use this
<input type="button">
than using this
<input type="submit">
In my specific case I had to stop ENTER from submitting the form and also simulate the clicking of the submit button. This is because the submit button had a click handler on it because we were within a modal window (inherited old code). In any case here's my combo solutions for this case.
$('input,select').keypress(function(event) {
// detect ENTER key
if (event.keyCode == 13) {
// simulate submit button click
$("#btn-submit").click();
// stop form from submitting via ENTER key press
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
});
This use case is specifically useful for people working with IE8.
Section 4.10.22.2 Implicit submission of the W3C HTML5 spec says:
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
Note: Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)
Therefore, a standards-compliant way to disable any implicit submission of the form is to place a disabled submit button as the first submit button in the form:
<form action="...">
<!-- Prevent implicit submission of the form -->
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<!-- ... -->
<button type="submit">Submit</button>
</form>
One nice feature of this approach is that it works without JavaScript; whether or not JavaScript is enabled, a standards-conforming web browser is required to prevent implicit form submission.
Giving the form an action of 'javascript:void(0);' seems to do the trick
<form action="javascript:void(0);">
<input type="text" />
</form>
<script>
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
alert('Hello');
}
});
});
</script>
This works for me
jQuery.each($("#your_form_id").find('input'), function(){
$(this).bind('keypress keydown keyup', function(e){
if(e.keyCode == 13) { e.preventDefault(); }
});
});
A nice simple little jQuery solution:
$("form").bind("keypress", function (e) {
if (e.keyCode == 13) {
return false;
}
});