I use Bootbox.js (http://bootboxjs.com/) to pop up forms in my application. Bootbox has an API for specifying callbacks on any custom buttons you may choose to add to your dialog. For example, here's an options object that gets passed into Bootbox:
var dialogOptions = {
message: bodyMessage,
className: uniqueClass,
closeButton: false,
onEscape: false,
title: i18n.t("common.loginHeader"),
buttons: {
login: {
label: i18n.t("common.signIn"),
className: "btn btn-success ",
callback: function () {
var user = $("#username").val();
var password = $("#password").val();
var toEncode = user + ":" + password;
fcr.api.authorization(window.btoa(toEncode), successCallback, errorCallback);
return false;
}
}
}
};
As you can guess, it's an authentication dialog. The "return false" in the callback prevents the dialog from closing (the authentication method will find and close it if successful). Other than that, it just gathers some form values and sends them along.
Thing is, since the button is not a "Submit" DOM element, it doesn't listen for the "Enter" key. To be honest, this is usually a blessing. But in this one particular case (username/password form), I constantly intuitively expect it to submit with the "Enter" key. If I try to add a Submit button to the form, the consistency of the visual "vocabulary" is lost. The button needs to be part of the dialog, not part of the form.
I could add a listener to the password field that listens for the enter key (code 13):
$('#password').keypress(function(e) {
if(e.which == 13) {
// do the submit?
}
});
But it seems kind of hack-ish. And I would have to abstract the callback into an action method of some sort so that either activity could call it. Not necessarily a bad thing, but I won't need that function anywhere else so it seems to be an abstraction I could avoid given an alternative. Is this the only way to get'r done, or does anybody know of something more elegant?
I don't know that I'd call it elegant, but one possibility would be to add your keypress listener to a higher parent, and then trigger the login button's click event:
Add a class to the login button:
login: {
className: "btn btn-success login-btn",
}
Add the listener to the modal itself (or, in this case, the form you injected):
$('.' + uniqueClass + ' form').on('keypress', function(e) {
if(e.which == 13) {
$('.login-btn').trigger('click');
}
});
With the requisite jsFiddle: https://jsfiddle.net/aLeqec2L/