0

For some reason my jQuery code is not able to find the button by class.

This is what I have:

$(document).ready(function () {
            $(".deleteItem").click(function () {
                alert("Handler for .click() called.");
            });
        });

The html I have for the button:

<input type="button" value="Remove" class="deleteItem btn btn-danger btn-xs pull-right" id="testDeleteItem">

When the page is loading, the button is not recognized. The button is in hidden div and its only shown when the user is hovering over a control.

What do I need to change to make this work?

halfer
  • 19,824
  • 17
  • 99
  • 186
Laziale
  • 7,965
  • 46
  • 146
  • 262
  • 3
    is the button dynamically loaded? – AmmarCSE Aug 17 '15 at 18:15
  • Is the button in an iframe? – Stryner Aug 17 '15 at 18:16
  • 1
    @AmmarCSE the button is dynamically loaded, yes, via c# code. but thats all done while the page elements are created on page_load, nothing async. – Laziale Aug 17 '15 at 18:17
  • Is jQuery included and is that JS included? – Popnoodles Aug 17 '15 at 18:17
  • simply use `'$(".deleteItem").on('click', function () {'` – Sushil Aug 17 '15 at 18:17
  • @Stryner no, its not in an iframe – Laziale Aug 17 '15 at 18:18
  • Does it work if you try to get button by ID? $('#testDeleteItem')... ? – Victor Levin Aug 17 '15 at 18:21
  • @Zealander no it doesn't recognize the button by ID as well – Laziale Aug 17 '15 at 18:22
  • You say button is in hidden control. Can you post code that shows/hides the button? – Victor Levin Aug 17 '15 at 18:26
  • FYI @ (http://getbootstrap.com/css/#buttons) : As a best practice, we highly recommend using the – Mike Horstmann Aug 17 '15 at 19:03
  • I would also strive to never pre-class an element with anything but pure bootstrap class declarations in the given order twitter's team defined in the documentation linked in previous comment. You could alternatively use your string of bootstrap classes starting with "btn....." and id the element with id="deleteItem" that would make it much cleaner, and also clarify your selector. Lastly, any bootstrap selectors are dot-notation classes when selecting ie: $("deleteItem.btn.btn-danger.btn-xs.pull-right" is the correct class based elem query in jQuery. – Mike Horstmann Aug 17 '15 at 19:06

1 Answers1

2

Use delegation for dynamically loaded content

$(document).ready(function () {
    $(document).on('click', '.deleteItem', function () {
            alert("Handler for .click() called.");
    });
});
Popnoodles
  • 28,090
  • 2
  • 45
  • 53
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53