In my web application, There is a table and Add button.
Whenever the user clicks on the Add button, from javascript, I load the new row to the table.
In the row, there is a element and for that class, I added the Select2 js-dropdown class when adding to the new row.
But when it was added, Js-dropdown class was not applied.
How can I add it?
this is the current code.
<table class="table table-striped" id="submissionTable">
<thead>
<tr>
<th>#</th>
<th>ITEM</th>
<th>QTY</th>
<th>MEASURE BY</th>
<th>UNIT PRICE</th>
<th>LINE TOTAL</th>
</tr>
</thead>
<tbody class="table-border-bottom-0">
<tr id="tablerow0"></tr>
</tbody>
</table>
This is the javascript code.
$(function () {
$("#add").click(function () {
var newRow = $(
'<tr id="tablerow' +
counter +
'"> ' +
"<td>" +
'<label id="CountItems"><strong>' +
counter +
"</strong></label>" +
"</td>" +
'<td width="40%">' +
'<select onchange="sendInfo(this)" class="form-select js-dropdown" data-id= ' + counter + ' name="Item_Id[' +
counter +
']" id="ItemId"' + counter + 'required="required" ' +
"</select>" +
"</td>" +
'<td width="10%">' +
'<input type="text" class="form-control" name="Qty[' +
counter +
']" value="1" id="Qty[' + counter + ']" onchange="calQtyBase(this)" data-QtyId= ' + counter + ' required="required" />' +
"</td>" +
'<td width="10%">' +
'<input type="text" class="form-control" name="MeasureBy[' +
counter +
']" value="" id="MeasureBy[' + counter + ']" readonly />' +
"</td>" +
'<td width="20%">' +
'<input type="text" class="form-control" name="Unit_Price[' +
counter +
']" value="0.00" id="UnitPrice[' + counter + ']" onchange="priceBase(this)" data-PriceId= ' + counter + ' required="required" />' +
"</td>" +
'<td width="20%">' +
'<input type="text" class="form-control" name="Line_Total[' +
counter +
']" value="0.00" id="LineTotal[' + counter + ']" required="required" />' +
"</td>" +
"<td>" +
'<button type="button" class="btn btn-danger" onclick="removeTr(' +
counter +
');">x</button>' +
"</td>" +
"</tr>"
);
var selectElement = newRow.find("select"); // Find the <select> element in the new row
// Populate the <select> element with options
dropdownOptions.forEach(function (option) {
var optionElement = $("<option>").val(option.Value).text(option.Text);
selectElement.append(optionElement);
});
newRow.appendTo("#submissionTable");
counter++;
return false;
});
});
2
Answers
If you want to select2 jquery plugin work on new select element added to DOM, you need to initialize it on this select.
edit
You have a syntax error, so it may not work for you.
replace
']" id="ItemId"' + counter + 'required="required" ' +
On
']" id="ItemId' + counter + '" required="required" ' +
I fixed this error see below.
A little different approach; sorry this is just a really really fast post here: