Fire on enter
A small JavaScript/jQuery snippet that triggers an action as soon as the Enter key is pressed in a field.
$("[fire-on-enter]").not('.fire-on-enter-bound').on("keypress", function(e) {
if (e.which == 10 || e.which == 13) eval($(this).attr("fire-on-enter"));
}).addClass("fire-on-enter-bound");
You use the script like this, for example:
<input type="text" fire-on-enter="doSomething()">
What's the deal with fire-on-enter-bound? I regularly use Ajax to load content and controls dynamically, and afterwards I run the JavaScript again each time to bind the keypress on newly loaded controls. The problem is that controls that already have the keypress bound get it bound a second time, so pressing Enter once fires the bound function twice. That's why there's the fire-on-enter-bound class: it is added to bound controls and prevents the event from being bound again.