I've got a form that has no submit button and it would be great if the form is still submitted when the user hits the enter key. I've tried adding a hidden submit button, which gives me the desired behavior in Safari, Firefox and Chrome, but the form is still not submitted in IE. Is there a standard way of doing this?
views:
55answers:
6Tested/cross-browser:
function submitOnEnter(e) {
var theEvent = e || window.event;
if(theEvent.keyCode == 13) {
this.submit;
}
return true;
}
document.getElementById("myForm").onkeypress = function(e) { return submitOnEnter(e); }
<form id="myForm">
<input type="text"/>
...
</form>
If there is no submit button, the form will degrade miserably if javascript is not available!
onKeyDown event of textbox or some control call a javascript function and add form.submit(); statement to the function.
Happy coding!!
Using jQuery (naturally):
$("#myForm input").keyup(
function(event){
if(event.keycode == 13){
$(this).closest('form').submit();
}
}
);
Give that a try.
This will require JavaScript. The easiest way to implement this with JavaScript if you don't know the language would be to use something like jQuery (much like what inkedmn said).
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
<!--
$(document).ready(function() {
$(document).keyup(function(event){
if(event.keycode == 13){ // This checks that it was the Enter key
$("#myForm").submit(); // #myForm should match the form's id attribute
}
});
});
//-->
</script>
</head>
<body>
<form id="myForm">
...
</form>
</body>
For more information on jQuery: http://docs.jquery.com/Tutorials:How_jQuery_Works#jQuery:_The_Basics
You know that you can just put a <button type="submit">submit</button>
there and change his position with css, right? position:absolute;left:-9999px;
Should do the trick. display:none
will not work tho.
This will also work if js is not loaded.
edit: However, if you chose to use js, do not forget to not submit if you have a textarea.