I am trying to append rows in a table which have some input tags and a select tag and I want to initialize select tag with jQuery Select2 library in order to do that I’ve found some code which initializes Select2 on appended select tag only when its just a select tag without any container div or td. I am a not much familiar with jQuery so please let me know how can I append the required code in:
<tbody class="items-list"> </tbody>
Here is the code which I found:
$(function() {
$("button").on("click", function() {
$(".items-list").append($('<select><option>test</option><select/>'));
});
// select the target node
var target = document.querySelector('.items-list');
if (target) {
// create an observer instance
var observer = new MutationObserver(function(mutations) {
//loop through the detected mutations(added controls)
mutations.forEach(function(mutation) {
//addedNodes contains all detected new controls
if (mutation && mutation.addedNodes) {
mutation.addedNodes.forEach(function(elm) {
//only apply select2 to select elements
if (elm && elm.nodeName === "SELECT") {
$(elm).select2();
}
});
}
});
});
// pass in the target node, as well as the observer options
observer.observe(target, {
childList: true
});
// later, you can stop observing
//observer.disconnect();
}
});
As you can see it is only appending the select element not any tr, td or div whenever I try to add any container Select2 doesn’t work. Here is the code that I want to append:
<tr>
<td> <span id="sr_no">'.$x.'</span> </td>
<td>
<div class="form-group">
<select class="form-control select2" style="width: 100%;" id="product-name'.$x.'" name="product_name[]">
<option selected="selected" disabled>Select Product</option>';
foreach($rows as $row){
<option value="'.<?php echo $row["product_id"]; ?>.'">'.<?php echo $row["product_id"]; ?>.' | '.<?php echo $row["product_name"]; ?>.'</option>
<?php } ?>
</select>
</div>
</td>
<td> <input type="text" name="rate[]" id="rate1" class="form-control"> </td>
<td> <input type="number" name="qty[]" id="qty1" min="1" class="form-control"> </td>
<td> <input type="text" name="amount[]" id="amount1" class="form-control"> </td>
<td> <input type="text" name="disc[]" id="disc1" value="0" class="form-control"> </td>
<td> <input type="text" name="total[]" id="total1" class="form-control"> </td>
<td>
<div class="btn-group btn-group-sm">
<button type="button" onclick="removeRow('.$row["product_id"].')" class="btn btn-danger"><i class="fas fa-trash"></i></button>
</div>
</td>
</tr>
Please let me know how can I do that. I’ll appreciate it