Enabling Switchery on dynamically added checkboxes

1.1k views Asked by At

I am dynamically adding rows to a table. Within each row is a checkbox. I then want to use switchery to change the styling. My problem is that when I add the first row then my code works nicely. When I add a second row then switchery seems to be added for a second time to the first checkbox. The checkbox on the second row (i.e. the one just added) is correctly converted to a switchery checkbox.

jQuery(document).on('click', '.add-product-from-modal', function() {        

    $('#product-list').append('<tr><td>Product Name</td><td>1</td><td><input name="isDelivery[]" class="switchery" value="1" type="checkbox"/></td><td><input name="deliveryDate[] "type="text" style="display: none" class="form-control deliveryDate"></td><td>&pound;1</td><td>TBC</td></tr>');                              

    var elems = Array.prototype.slice.call(document.querySelectorAll('.switchery'));

    elems.forEach(function(html) {
      var switchery = new Switchery(html, {size: 'small'});
    });

    return false;

});

First row ...

This is the after the first row

Second row ..

This is after the second row

You can see this as a fiddle at https://jsfiddle.net/9puL9je1/ - click "Add a new row" to see what I am talking about

1

There are 1 answers

0
Jesus Carrasco On BEST ANSWER

I make some modifications to your code. Basically i identify each element your find with the queryselector always does from all DOM, thats why always duplicated, i jus put an id for each new row, like an index, and for every new row switchery will create.

i put the code change below, hope this help.

var count = 0;
jQuery(document).on('click', '.add-product-from-modal', function() {        

    $('#product-list').append('<tr><td>Product Name</td><td>1</td><td><input name="isDelivery[]" id="'+count+'" class="switchery" value="1" type="checkbox"/></td><td><input name="deliveryDate[] "type="text" style="display: none" class="form-control deliveryDate"></td><td>&pound;1</td><td>TBC</td></tr>');       

    var elems = document.getElementById(count);  
    var switchery = new Switchery(elems, {size: 'small'});
    count++;

    return false;

});

Here is the fiddle updated sample