How do I get an element via jquery in an object created in the bootbox.js plugin?

2

I have an object created inside a container-fluid div. I create the object Bootbox with no problem whatsoever to generate a modal confirm (code below).

$("div.container-fluid").on("click", "button#geraModal", function() {
    bootbox.confirm({
       title: "What is your real name?",
       message: "<div class="row"> <div class="col-md-3>" +
                "<div id="exemplo"> Quero acessar essa DIV </div>" +
                "</div> </div>",
       callback: function(result) {
          if (result === false) {
             alert("Confirm Cancel");
          } else {
             alert("Hi <b>"+result+"</b>");
          }
       }
    });
});

When I try to access some modal object via jQuery it does not work. I can not access any modal element via jQuery. If I want to perform a function. It only works if I put a Javascript inside div with a onclick event (for example).

I'm trying to access the div of the above example as follows:

$("div.container-fluid").on("click", "div#exemplo", function() {
    // Faça algo
    alert("Não passa aqui");
});
    
asked by anonymous 05.10.2015 / 12:59

1 answer

0

The problem happens because when the Jquery event handler evaluates the element you reference does not yet exist (since it is dynamically created). So you need to tell the event handler that it should match the selector with all the elements that exist now and in the future. To do this, use the .live event. ( link )

Your code looks like this:

Jquery

$("#open").click(function (e) {
    bootbox.confirm({
            title: "BOOTBOX",
            message: '<div class="row"><div class="col-md-offset-1"> <p> Options</p> </div> </div>'+
                            '<div id="row1" class="row text-center center-block"> <div class="col-md-offset-3 col-md-3 btn btn-default active" id="exemplo1" > <p> Example 1</p> </div> <div class="col-md-3 btn btn-default" id="exemplo2">  <p> Example 2</p> </div></div>',
            className: "saveExample",
            callback: function(result){
                if (result === true){
                    alert("Test 123");
                }
            }
        });
     });

$("#exemplo1").live("click", function(event){
    alert( "Div 'exemplo1' clicada" ); 
});

$("#exemplo2").live("click", function(event){
    alert( "Div 'exemplo2' clicada" ); 
});

HTML

<a href="#" class="btn btn-inverse" id="open">OPEN BOOTBOX</a>

Example running on JsFiddle

Update

The .live() event is deprecated starting with version 1.7 of Jquery, use the event .on() :

$(document).on("click", "#exemplo2", function(event){
    alert( "Div 'exemplo2' clicada" ); 
});

delegate also works:

$(document).delegate("#exemplo1", "click", function(event){
    alert( "Div 'exemplo1' clicada" ); 
});

New example in JsFiddle

I hope I have helped you.

    
05.10.2015 / 13:11