As the title suggests, I want to add the Enter key as an event handler for Bootbox.js. When you an alert() popup is called, you can press enter to dismiss it, but that is not the case with Bootbox.js. I do not know how to get access to the button inside Bootbox.js to add an event handler. Any suggestions?
A confirm dialog with a cancel and a confirm button. Pressing the ESC key or clicking close () dismisses the dialog and invokes the callback as if the user had clicked the Cancel button. Confirm dialogs require a callback function.
js is a small JavaScript library which allows you to create programmatic dialog boxes using Bootstrap modals, without having to worry about creating, managing, or removing any of the required DOM elements or JavaScript event handlers.
In order for the button to take focus, it should be defined with the "btn-primary" class name:
className:
main: {
className: "btn-primary", ...
}
I see this post has no answer yet for case when user has focus in the form itself
Here's how to do it :
Code :
$(document).on("submit", ".bootbox form", function(e) {
e.preventDefault();
$(".bootbox .btn-primary").click();
});
bootbox.dialog({
title : "Title",
message : $("#templateWithForm").html(),
onEscape : true,
buttons :
{
success : {
label : "OK",
className : "btn-success btn-primary",
callback : function() {
// do something...
}
}
}
})
Explanation :
First bit of code will catch the "submit" event for all bootbox dialogs with forms in it and prevent the submit with preventDefault()
it will then emulate a click on the button that has className : "btn-primary"
(Note that it's going to trigger a click to all bootbox dialogs so you might wanna change it for your use case if you have more than a dialog on the page at once)
Second bit of code is a simple dialog calling. Important parts are
onEscape : true
if you want to close the dialog with Escape keyclassName : "btn-success btn-primary"
btn-success can obviously be changed to fit your needsHope this helps the next person !
You can just add 'bootbox-accept' className for the button you want to click on enter key press.
Example:
bootbox.dialog({
title : "Title",
message : "Your Message",
onEscape : true,
buttons :
{
success : {
label : "OK",
className : "btn-success bootbox-accept",
callback : function() {
// do something...
}
},
cancel:{
label : "Cancel",
className : "btn-danger",
callback : function() {
// do something...
}
},
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With