Reputation: 355454
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?
Upvotes: 3
Views: 1754
Reputation: 815
This may be accomplished cross-browser by keeping the submit input intact and some creative CSS. By keeping the input available, you also preserve support for screen readers.
.no-submit-button {
position: relative;
}
.hidden-submit {
border: 0;
clip: rect(0, 0, 0, 0);
height: 1px;
margin: -1px;
padding: 0;
position: absolute;
width: 1px;
}
<form class="no-submit-button">
<input class="hidden-submit" type="submit" value="Submit">
</form>
Upvotes: 0
Reputation: 342625
Tested/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!
Upvotes: 2
Reputation: 22156
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.
Upvotes: 0
Reputation: 7230
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
Upvotes: 0
Reputation: 28205
Using jQuery (naturally):
$("#myForm input").keyup(
function(event){
if(event.keycode == 13){
$(this).closest('form').submit();
}
}
);
Give that a try.
Upvotes: 2
Reputation: 9942
onKeyDown event of textbox or some control call a javascript function and add form.submit(); statement to the function.
Happy coding!!
Upvotes: 0