skip to Main Content

I have’a modal ( I use twitter bootstrap 2.3.2 and I need to use it please dont say to use bootstrap3), and I want to show different content based on the clicked button. In other words, there are multiple buttons that are added dynamically into dom, and based on the clicked button, I need to show different content. Currently, it always shows the content of the first clicked button no matter where I’am pushing. Here is my code:

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button>
        <h3 id="myModalLabel">Query Name</h3>
    </div>
    <div class="modal-body">

       <div id="graph" style="position:relative;overflow:hidden;cursor:default;" class="{{getViewType}}">
           <center id="splash" style="padding-top:230px;">
               <img src="../images/loading.gif">
           </center>
       </div>

    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    </div>
</div>

And this is my handler:

$(document).on('hidden','#myModal',function(){
    console.log('it comes here');  // this is printed every time I close modal
     $(this).removeData('modal');
});

2

Answers


  1. Perhaps check that the id’s of the dynamically added buttons are unique. Also that any function code that will run when they’re clicked, is also dynamically added otherwise it won’t run. It would certainly help to see the code for the buttons.

    Login or Signup to reply.
  2. DEMO

    Ok.. I prefer .shown event of modal for this case and a global variable to store the data of clicked button as below

    var dataToShow=""; //global variable
    
    //A button click event to store data
    $('button').on('click',function(){
        dataToShow=$(this).text();//For DEMO purpose am storing text of button clicked in dataToShow
    });
    
    
    $(document).on('shown','#myModal',function(){
        //Will be triggered when modal is opened
        alert(dataToShow);//Just for verification
        $('.modal-body .datadisplay').html(dataToShow); 
        //assign the value in a separate div inside modal-body so that you will not replace anything else each time
    });
    

    Now since the button is dynamically created, I would suggest to use event delegation here to attach event to button

    $(document).on('click','.yourbuttonClass',function(){
         dataToShow=$(this).text();
    });
    

    Now if you want you can make use of

    $(document).on('hidden',"#myModal",function(){
        //clear the contents inside an element added i.e. .datadisplay inside modal-body
        $('.modal-body .datadisplay').empty();   
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search