0

I have a simple link that will fire an ajax call and change a status, and I want that new status reflected (instantly) on the modal form.

Problem is: when I click the link that is on the modal form (below), nothing happens.

<a title="Autoplay" data-placement="top" data-toggle="tooltip" class="glyphicon glyphicon-stop" id="autoplayStatus" href="#"></a>

In $(document).ready(), I have this:

$("#autoplayStatus").click(function(event){
        alert('test');
    })

Is there something I should do to ensure that jQuery can select and bind to objects on a modal form?

DrDamnit
  • 4,736
  • 4
  • 23
  • 38

1 Answers1

2

To ensure that jQuery binds to buttons (or other stuff) in modals created by Bootstrap, you should write your event handler like this:

$(document).ready(function() {
    $('.container').on('click', '#autoplayStatus', function() {
        alert('Ohai!');
    });
});

and then, in my example, wrap the anchor tag in a container:

<div class="container">
    <a title="Autoplay" data-placement="top" data-toggle="tooltip" class="glyphicon glyphicon-stop" id="autoplayStatus" href="#"></a>
</div>

On a sidenote, it's better practice to use <button> instead of <a> when creating, well, a button. =)

The Bear
  • 223
  • 3
  • 6
  • Out of curiosity, why elaborate to such a point as creating a div, and then using the .on to bind the click to the id within that div? Better practice or is there performance differences? – DeeKayy90 Mar 21 '14 at 00:36
  • 1
    Well, let's say that '.container' contains a range of buttons that are dynamically generated. In that case, binding to the '.container' instead of the buttons prevent you from having to bind the buttons again once they are created. You can think of it as registering a click on the whole container, but only caring about it if it's on the given selector, '#autoplayStatus' in this case. Forgot to add: Not sure if there are any performance benefits, but your JavaScript sure gets a lot cleaner. – The Bear Mar 21 '14 at 00:43
  • The code works, but I have two elements (checkboxes) in the div. I have used the class / container function so I only have to write one function to manage these, but each of the checkboxes carries with them a data attribute that is requried for an ajax call. $(this) no longer refers to the checkbox clicked, but rather the div. How do I refer to the checkbox that was clicked (specifically) so I can extract that id from the data attribute? – DrDamnit Mar 21 '14 at 01:56
  • [This SO answer](http://stackoverflow.com/a/5097214/1974124) is hopefully going to be helpful. You basically define `this` using `context`. – The Bear Mar 21 '14 at 10:00