gpt4 book ai didi

c# - 如何使用 jQuery 复制带有下拉列表的表行

转载 作者:太空狗 更新时间:2023-10-29 16:34:33 26 4
gpt4 key购买 nike

我有一个表格,我想在按下添加新 链接后​​复制它的最后一行。当我的行中只有 TextBoxes 时,它完全可以正常工作,但当有下拉菜单时则不会。请帮我修改jquery代码。这是表格的代码:

<div><a href="#" id="addNew">Add New</a></div>
<table id="dataTable">
<tr>
<th>Item</th>
<th>Cost</th>
<th></th>
</tr>
@if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr>
<td>@Html.DropDownListFor(a => a[j].fk_purchase_id, (SelectList)ViewBag.fk_purchase_id, null, htmlAttributes: new { @class = "form-control"})</td>
<td>@Html.TextBoxFor(a => a[j].cost, htmlAttributes: new { @class = "form-control" })</td>
<td>
@if (j > 0)
{
<a href="#" class="remove">Remove</a>
}
</td>
</tr>
j++;
}
}
</table>

下面是需要改进的代码:

 <script>
$(function () {
//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone();
alert($trNew.html);
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('<a href="#" class="remove">Remove</a>');
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
$(this).attr('value', '');
}
});

$trLast.after($trNew);
});

});
</script>

我试图通过将 input 更改为 select 来修改这一行,但没有帮助

var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);

最佳答案

首先在你的表中添加 tbody,如:

        <table id="dataTable">
<thead>
<tr>
<th>Item</th>
<th>Cost</th>
<th></th>
</tr>
</thead>
<tbody>
@if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr>
<td>@Html.DropDownListFor(a => a[j].fk_purchase_id, (SelectList)ViewBag.fk_purchase_id, null, htmlAttributes: new { @class = "form-control"})</td>
<td>@Html.TextBoxFor(a => a[j].cost, htmlAttributes: new { @class = "form-control" })</td>
<td>
@if (j > 0)
{
<a href="#" class="remove">Remove</a>
}
</td>
</tr>
j++;
}
}
</tbody>
</table>

你的脚本是:

    <script>
$(function () {
$("#addNew").click(function (e) {
e.preventDefault();
var last = $('#dataTable>tbody>tr:last');
if (last.length > 0) {
var name = last.children().find('input,select')[0].name;
var index = Number(name.replace(/[^0-9]/gi, '')) + 1;
var tr = ('<tr>' + last.html().replace(/[0-9]+__/gi, index + '__') + '</tr>') .replace(/\[[0-9]+\]+[.]/gi, '[' + index + '].');
$('#dataTable tbody').append(tr);
}
});

});
</script>

关于c# - 如何使用 jQuery 复制带有下拉列表的表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43794893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com