I have dropdowns that are being appended dynamically on a page. However, I could not assign the value to the select2. Anyone can help me with this?
Below is what I have try to do to assign the data to select2, but still cannot. Where am I missing??
1. $('select.row-item').eq(index).val(item.itemID);
2. $('.row-item:eq("' + index + '")').val('"' + item.itemID + '"')
3. var $row = $(html)
a. $row.find("row.item option[value=" + item.itemID + "]").prop("selected", true);
b. $row.find('select .row-item').val(item.itemID).trigger('change');
$(function() {
var data = data1
var html = '';
html += '<thead><tr>';
html += '<th>Item</th>';
html += '<th>Description</th>';
html += '<th>Qty</th>';
html += '<th>Total</th>';
html += '</tr></thead>';
html += '<tbody class="acc_table">';
data.forEach((item, index) => {
html += '<tr class="acc-row">';
html += '<td><select class="row-item"><option label="Choose One"> </option><option value="10">ITEM 1</option><option value="20">ITEM 2</option></select></td>';
html += '<td><input class="row-desc" type="text" value="' + item.itemName + '"></td>';
html += '<td><input class="row-qty" type="text" onkeyup="onlyDecimal(this)" value="' + item.itemQty + '"></td>';
html += '<td><input class="row-totalamount" type="text" value="' + item.totalAmount + '" disabled></td>';
html += '</tr>';
//at here I assign the data to select2
$('select.row-item').eq(index).val(item.itemID);
});
html += '</tbody>';
$('.item tbody').empty();
$('.item').append(html);
$('.row-item:last').select2();
$('.item').DataTable({
"paging": false,
"ordering": false,
"info": false,
"searching": false,
});
})
const data1 = [{
"itemID": "10",
"itemName": "Item 1",
"itemQty": "1",
"totalAmount": "50.00"
},
{
"itemID": "20",
"itemName": "Item 2",
"itemQty": "5",
"totalAmount": "150.00"
}
]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js"></script>
<table class="item">