Bootbox: Make the default button work with the ENTER key?

As the name suggests, I want to add an Enter key as an event handler for Bootbox.js. When you call the alert () popup, you can press Enter to cancel it, but this is not the case with Bootbox.js. I don't know how to access the button inside Bootbox.js to add an event handler. Any suggestions?

+3


source to share


3 answers


For a button to be focused, it must be defined with the class name "btn-primary":



className:
main: {
      className: "btn-primary",  ...
}

      

+5


source


I see that this post does not yet have an answer for the case where the user has focus on 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:



The first bit of code will catch the submit event for all bootbox dialogs with forms in it and prevent the submission with preventDefault()

, then emulates a click on the button withclassName : "btn-primary"

(Note that this will trigger a click on all the loading window dialogs, so you can change it for your use case if you have more on the page than on the page)

The second bit of code is simple dialogue. Important parts

  • onEscape : true

    if you want to close the dialog with the Escape key
  • className : "btn-success btn-primary"

    btn-success can obviously be modified to suit your needs.

Hope this helps the next person!

+4


source


looking at bootbox examples , when an alert (or whatever) is triggered, the main button is in focus, allowing you to press enter to hide the alert again. Maybe check that you don't do anything else after the warning that would enter the focused state of the buttons ... maybe curious, who really knows?: D

0


source







All Articles