Đôi khi bạn cần tạo form động, cho phép người dùng tùy ý thêm field dữ liệu vào form
Dưới đây là đoạn code thêm fields động vào form dùng trong dự án .net core, view razor
<!-- html code -->
<table class="table table-responsive" id="product-table">
<tr>
<th>TÊN SẢN PHẨM</th>
<th>SỐ LƯỢNG</th>
<th>
<a href="javascript:void(0);" class="btn btn-sm btn-success">
<i class="fas fa-plus" onclick="addNewRow()"> Thêm sản phẩm</i>
</a>
</th>
</tr>
<tr>
<td id="col0">
<input class="form-control" type="text" asp-for="Products" />
</td>
<td id="col1">
<input class="form-control" type="text" asp-for="ProductCount" />
</td>
<td id="col2">
</td>
</tr>
</table>
<!-- javascript code -->
<script>
/* This method will add a new row */
function addNewRow() {
let table = document.getElementById("product-table");
let rowCount = table.rows.length;
let cellCount = table.rows[0].cells.length;
let row = table.insertRow(rowCount);
for (let i = 0; i < cellCount; i++) {
let cell = 'cell' + i;
cell = row.insertCell(i);
if (i < cellCount - 1) {
let copycel = document.getElementById('col' + i).innerHTML;
cell.innerHTML = copycel;
} else {
cell.innerHTML = '<a href="javascript:void(0);" class="btn btn-danger btn-sm"><i class="fas fa-trash" onclick="deleteRow(this)"> Xóa sản phẩm</i></a>';
}
}
}
/* This method will delete a row */
function deleteRow(ele) {
let table = document.getElementById('product-table');
let rowCount = table.rows.length;
if (rowCount < 3) {
alert("There is no row available to delete!");
return;
} else {
if (ele) {
//delete specific row
ele.parentNode.parentNode.parentNode.remove();
} else {
//delete last row
table.deleteRow(rowCount - 1);
}
}
}
</script>
[Happy coding]
Không có nhận xét nào:
Đăng nhận xét