0

I created a form with checkbox + wrapper, i.e :

<form>
  <div class="input-wrapper">
      <input type="checkbox" name="item[]" value="1">
  </dv>
  <div class="input-wrapper">
      <input type="checkbox" name="item[]" value="2">
  </div>
  <div class="input-wrapper">
      <input type="checkbox" name="item[]" value="3">
  </div>
</form>

and this toggle check is working:

$(".input-wrapper").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.prop('checked', !$checkbox[0].checked);
 });

But when I load other checkbox from ajax, i.e:

$.post(
     '/my/url',
     {...my data...},
      function(data){
           if(data != 'failed'){
               //return new checkbox + wrapper too and append it at the end of the form
                $('form').append(data);
           }
      }
 );

the Toggle check is not working just for the loaded/appended element.

How to fix this ? how to properly create a script that affect all the element even for the loaded one ?

thanks.

egig
  • 4,189
  • 4
  • 24
  • 48

2 Answers2

2

The way you're binding the click listener will bind to all .input-wrapper elements currently in the DOM.

You may either bind the new ones for clicks separately, or delegate the listener to a parent object that will stay in the DOM (e.g. $(document).on("click", ".input-wrapper", function (){//Do Stuff});)

DRobinson
  • 4,341
  • 19
  • 29
1

Try this slight modification:

$("form").on("click", ".input-wrapper", function () { 
    var $checkbox = $(this).find(':checkbox');
    $checkbox.prop('checked', !$checkbox[0].checked);
});

and let me know how it goes.

Madison May
  • 2,493
  • 2
  • 17
  • 29