javascript - chosen plugin not working with dynamically created rows in a table -
i must beginner in jquery try figure out , solve problems myself. have problem , stuck have table dynamically added rows , select box each purpose of single delete or multiple delete, works fine except when rows added chosen applied select boxes aren't functioning no matter nothing works.
html
<table id="datatable"> <tr> <th><input type="checkbox" id="selectall" value="selectall"/></th> <th>field-1</th> <th>field-2</th> <th>field-3</th> <th>field-4</th> <th>field-5</th> </tr> <tbody> <tr> <td><input type="checkbox" class="check"></td> <td> <select name="input-1[]" class="chosen_select_l"> <option></option> <option>option 1</option> <option>option 2</option> <option>option 3</option> </select> </td> <td><input name="input-2[]" type="text" class="chosen_text"></td> <td><input name="input-3[]" type="text" class="chosen_text"></td> <td><input name="input-4[]" type="text" class="chosen_text"></td> <td> <select name="input-5[]" class="chosen_select_m"> <option></option> <option>option 1</option> <option>option 2</option> <option>option 3</option> </select> </td> </tr> </tbody> </table> <input type="button" value="add field" onclick="addrow('datatable')" /> <input type="button" value="remove field" onclick="deleterow('datatable')" />
js
$(".chosen_select_l").chosen({ disable_search_threshold: 10, no_results_text: "oops, nothing found!" }); $(".chosen_select_m").chosen({ disable_search_threshold: 10, no_results_text: "oops, nothing found!" }); $(document).ready(function() { $('#selectall').click(function(event) { if(this.checked) { $('.check').each(function() { this.checked = true; }); }else{ $('.check').each(function() { this.checked = false; }); } }); }); function addrow(datatable) { var table = document.getelementbyid(datatable); var rowcount = table.rows.length; if(rowcount < 11){ var row = table.insertrow(rowcount); var colcount = table.rows[1].cells.length; for(var i=0; i<colcount; i++) { var newcell = row.insertcell(i); newcell.innerhtml = table.rows[1].cells[i].innerhtml; } }else{ alert("maximum fields 10."); } } function deleterow(datatable) { var table = document.getelementbyid(datatable); var rowcount = table.rows.length; for(var i=2; i<rowcount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childnodes[0]; if(null != chkbox && true == chkbox.checked) { if(rowcount <= 1) { alert("cannot remove fields."); break; } table.deleterow(i); rowcount--; i--; } } }
i tried giving different ids or class names, visually looks fine not single select box working except in first row wasn't dynamically created.
i've created jsfiddle guys check out. appreciated. thanks
here corrected fiddle. need destroy chosen using
$(".chosen_select_l").chosen('destroy');
before getting innerhtml , re-initialize after appending contents.
Comments
Post a Comment