I've seen some other questions around this, but none for Prototype.
I have a form without a submit button (uses a styled link that calls some javascript).
What's the best way to detect a enter keypress in all the input fields and submit the form?
Thanks!
I've seen some other questions around this, but none for Prototype.
I have a form without a submit button (uses a styled link that calls some javascript).
What's the best way to detect a enter keypress in all the input fields and submit the form?
Thanks!
Share Improve this question edited Dec 28, 2011 at 11:45 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Sep 9, 2010 at 9:44 Brian ArmstrongBrian Armstrong 19.9k17 gold badges118 silver badges144 bronze badges 1- I can't offer any Prototype-specific advice, but have you considered adding a submit button and then hiding it with Prototype/JS? It's not the answer you want, but it degrades nicely. – David Thomas Commented Sep 9, 2010 at 9:51
3 Answers
Reset to default 10This is an example of the kind of thing you could use:
$('input').observe('keypress', keypressHandler);
function keypressHandler (event){
var key = event.which || event.keyCode;
switch (key) {
default:
break;
case Event.KEY_RETURN:
$('yourform').submit();
break;
}
}
It is the same as above but does not need to set a function:
$('input').observe('keypress', function(event){
if ( event.keyCode == Event.KEY_RETURN || event.which == Event.KEY_RETURN ) {
// enter here your code
Event.stop(event);
}
});
With Prototype:
document.observe("dom:loaded", function() {
$$('form').each(function(f) {
$(f).select("input").each(function(e) {
e.observe('keypress', function(event) {
if ( event.keyCode == Event.KEY_RETURN || event.which == Event.KEY_RETURN ) {
this.form.submit();
}
});
});
});
});