Rob Wilkerson Rob Wilkerson - 3 months ago 6
HTML Question

Enter triggers button click

I have a page with two buttons. One is a

<button>
element and the other is a
<input type="submit">
. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press
<Enter>
, the button element's
click
event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the
<Enter>
key that was pressed, I'm just negating it:

$('form').keypress( function( e ) {
var code = e.keyCode || e.which;

if( code === 13 ) {
e.preventDefault();
return false;
}
})


As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted. Does anyone know of a more sophisticated technique for doing this? Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

Answer

The obvious pitfall is multi-line <textarea>'s where you can no longer insert a newline, effectively making it a single-line input element.

The right way to solve this does not involve javascript at all, just some layout changes and styling.

You need to change the DOM's order of the buttons. Any other way of solving this is working against the browser instead of with it, and that is a fools errand.

It doesn't have to ruin the layout. The order of the buttons only has to be changed in the DOM/markup, not in the rendered layout - use positioning or floating to make the layout you want, independent of the order of the button elements.

If you have trouble figuring out how, let me know and i'll lend a hand ;)

Comments