In my web application, I'm dynamically adding new rows to a table using JavaScript.
Each row contains an element where data is loaded from the ViewBag, and I also want to apply the Select2 class to this element.
Here is the current code snippet:
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="443721282127307604706a756a746936276a74">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.6.4.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4635232a232532740672687768766b34256876">[email protected]</a>/dist/js/select2.min.js"></script>
<div class="table-responsive text-nowrap">
<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>
<p>
<button id="add" type="button" class="btn btn-primary">Add</button>
</p>
</div>
The JavaScript code for dynamically adding rows is as follows:
var counter = 1;
var dropdownOptions = @Html.Raw(Json.Encode(ViewBag.Item_ID));
$(function () {
$("#add").click(function () {
var newRow = $(
'<tr id="tablerow' +
counter +
'" class ="poSet"> ' +
"<td>" +
'<label id="CountItems"><strong>' +
counter +
"</strong></label>" +
"</td>" +
// Rest of the row creation logic
);
var selectElement = newRow.find("select");
dropdownOptions.forEach(function (option) {
var optionElement = $("<option>").val(option.Value).text(option.Text);
selectElement.append(optionElement);
});
newRow.appendTo("#submissionTable");
selectElement.select2();
counter++;
return false;
});
});
When the rows are added, the view looks like this:
https://i.sstatic.net/6wMUA.png
The width of the data element appears incorrectly on the first row and then corrects itself in subsequent rows.
There is also an issue with the appearance of the Select2 combo box, it seems to be missing the form-control class. How can I resolve these issues?