`<script>
'use strict';
$(document).ready(function() {
$(".chzn-select").chosen();
$('#example-4').on('click', '.ui-data-table-delete', function() {
var rowIndex = $(this).closest('tr').index();
delete_row(rowIndex);
});
// Delegate the input event to the table body
$('#example-4').on('input', 'tr:last input', function() {
// Check if all fields in the last row are filled
var isRowFilled = true;
$(this).closest('tr').find('input').each(function() {
if ($(this).val() === '') {
isRowFilled = false;
return false; // Exit the loop early if any field is empty
}
});
// If all fields are filled, trigger the add_row function
if (isRowFilled) {
add_row();
}
});
});
function add_row() {
var table = document.getElementById("example-4");
var t1 = table.rows.length;
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.textContent = t1;
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell4.className = 'abc';
cell3.className = 'abc';
// chzn-select
var select = $('<select class="chzn-select" style="width:200px" name="item[' + t1 + ']"></select>');
<?php foreach ($item_data as $value):?>
select.append('<option value="<?= $value->PKItemID; ?>"><?= $value->ItemName; ?></option>');
<?php endforeach;?>
select.appendTo(cell2);
select.chosen();
$('<input class="tabledit-input form-control input-sm" type="number" min="1" name="qty['+t1+']">').appendTo(cell3);
$('<input class="tabledit-input form-control input-sm" type="text" name="manufactureID['+t1+']">').appendTo(cell4);
$('<a href="#" class="btn btn-sm btn-danger ui-data-table-delete"><i class="feather icon-trash"></i></a>').appendTo(cell5);
}
function delete_row(rowIndex) {
var table = document.getElementById("example-4");
if (rowIndex >= 0 && rowIndex < table.rows.length) {
table.deleteRow(rowIndex);
// (rowIndex < table.rows.length) , Yeah well this ensures that
// the header row is not deleted.
// Adjust index numbers after deleting row
for (var i = rowIndex; i < table.rows.length; i++) {
console.log(i);
table.rows[i].cells[0].textContent = i;
// The hidden index is maintained well by the in
// built deleteRow function.
// We are just making the visible index and the hidden
// the same.
}
} else {
console.error('Invalid row index:', rowIndex);
}
}
</script>
The chosen select is fine when I don’t include the add row functionality based on whether the last row is filled or not. But when I include it chosen is not working. The other thing I noticed that sometimes chosen is applied but then add row based on user input doesn’t work. I do have a separate add_row button to add rows.
I tried using select2 library but it is messing with the css of the template.