Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery functions not working in a modal of Bootstrap

I use Bootstrap v2.X in my proyect and I want to open a file external using modal function.

First, the code I should use is:

<a href="view_graphics.php" class="btn btn-warning btn-large" data-toggle="modal">Graphics</a>

but it doesn't work for me. Then I use:

<a href="view_graphics.php" id="graphics" class="btn btn-warning btn-large">Graphics</a>

and I put code Jquery:

$('a#graphics').click(function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            if (url.indexOf('#') == 0) {
                $(url).modal('open');
            } else {
                $.get(url, function(data) {
                    $('<div class="modal hide fade modal-graphics">' + data + '</div>').modal();
                }).success(function() { $('input:text:visible:first').focus(); });
            }
        });

And It works!.

Well, but it doesn't the principal problem. The problem is when the modal is open, don't work my code jQuery.

This is my modal external:

<div class="modal-header">
    <a class="close" data-dismiss="modal">x</a>
    <h3>Titulo modal</h3>
</div>
<div class="modal-body">
    <div class="window">
        <div class="nom_epi"></div>
    </div>
</div>
<div class="modal-footer">
    <a class="btn btn-primary" href="javascript:print();">Imprimir</a>
    <a class="btn" data-dismiss="modal">Cerrar</a>
</div>

If I put the code in the file original:

$(document).ready(function() {
$('.nom_epi').click(function() { alert("hello"); });
});

It doesn't work! The external modal ignores Jquery code of the original file. It's strange because the bootstrap CSS interpreted good.

I think it is due to the jQuery code I use to open the external modal.

like image 481
Alexander Avatar asked Dec 09 '22 17:12

Alexander


2 Answers

You're binding the event on document ready, so it only binds to elements that exist at that time. I suggest using the on() function instead.

The suggestion David gives in his comment should work fine:

$('body').on('click', '.nom_epi', function() { alert("hello"); })

Generally you would try and bind the function to something further down the DOM tree, but these modals are usually direct children of <body>

like image 111
daveyfaherty Avatar answered Dec 28 '22 06:12

daveyfaherty


Consider if you click anywhere apart from your required DOM object and it still triggers the function execution; it will be kind of a mess. Hence, binding click event to body is not a recommended way as it will be heavy event binding. Try to to use window.onLoad function instead of document.ready within which you will keep binding function execution with same DOM object.

$(window).load(() => {

  $('.nom_epi').click((e) => { 
      console.debug("it is working"); 
  });

});
like image 30
Sankeerna Reddy Avatar answered Dec 28 '22 06:12

Sankeerna Reddy