0
  • I am trying to learn jquery.
  • in jquery I am using change method.
  • but its not displaying this alert ---> alert("I am inside change");
  • can you tell me how to fix it.
  • providing my code below.

http://jsfiddle.net/b8yx6f16/

 $('#checkIDGrid').change(function() {
     alert("I am inside change");
    if(this.checked) {
        var returnVal = confirm("Are you sure?");
        $(this).prop("checked", returnVal);
    }
   // $('#textbox1').val(this.checked);        
});
  • 1
    coudl you post the html including `#checkIDGrid`? – Scaramouche Apr 04 '18 at 18:57
  • You should include just the relevant part of the code in the question. – Adriano Martins Apr 04 '18 at 18:59
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Apr 04 '18 at 19:01
  • A good tip is to add `alert($('#checkIDGrid').length)` just before your `.change()` code - if it alerts "0" then the element doesn't exist and your event handler will have nothing to wire up against. If the element is created *after* this, then you have "dynamically generated elements" and need to use either event delegation or re-write the event. – freedomn-m Apr 04 '18 at 19:04

2 Answers2

3

Try this:

   $(document).on('change', '#checkIDGrid', function() {
         alert("I am inside change");
        if(this.checked) {
            var returnVal = confirm("Are you sure?");
            $(this).prop("checked", returnVal);
        }
       // $('#textbox1').val(this.checked);        
    });

http://jsfiddle.net/wj1z3dnp/

Eliellel
  • 1,326
  • 1
  • 7
  • 14
  • hey can you explain your code so that in future I can solve it by myself –  Apr 05 '18 at 01:34
  • Basically for the dynamic elements, in order for your event handler to be executed, you can either call `$("#id").on("click", fn);` after you insert them into the DOM, or bind the event to a static element that always in the DOM, such as `$(document)`. My code here is doing the latter. – Eliellel Apr 05 '18 at 13:07
1

It's because #checkIDGrid doesn't exist on the page until the grid populates, but the change event listener is bound immediately. You can use a delegate binding to avoid this issue:

$(document).on('change', '#checkIDGrid', function() {

A delegate binding is attached to a parent element and is triggered even if the child element is added to the DOM after the listener is attached.

sliptype
  • 2,235
  • 10
  • 23