动态添加表格行时如何继承指定输入框的值?
解决点击添加按钮后新行Email输入框无法继承登录用户用户名的问题
问题根源
你的代码存在两个核心问题:
- 所有Email输入框使用了重复的
id="email",违反HTML中ID必须唯一的规则,可能导致选择器失效。 - 克隆行后统一清空所有文本输入框的值,直接导致新行的Email字段为空。
修复步骤
1. 修改视图代码(修复重复ID问题)
将Email输入框的id替换为class,同时移除删除按钮的重复ID:
<table id="dataTable" border="0" cellpadding="0" cellspacing="0"> <tr> <th>Contact Name</th> <th>Contact No</th> <th>Email</th> <th></th> </tr> @if (Model != null && Model.Count > 0) { int j = 0; foreach (var i in Model) { <tr style="border:1px solid black" class="data"> <td>@Html.TextBoxFor(a => a[j].ContactName)</td> <td>@Html.TextBoxFor(a => a[j].ContactNo)</td> <!-- 将id改为class,避免重复 --> <td>@Html.TextBoxFor(a => a[j].Email, new { @class="email-input" })</td> <td> @if (j > 0) { <!-- 移除重复id,仅保留class --> <a href="#" class="remove">Remove</a> } </td> </tr> j++; } } </table>
2. 修改jQuery代码(保留Email初始值)
先存储登录用户的Email初始值,克隆新行时为Email输入框赋值:
$(document).ready(function () { // 存储第一行的Email值(即登录用户用户名) const loggedInEmail = $(".email-input").first().val(); // 添加新行 $("#addNew").click(function () { var $trLast = $("#dataTable tr:last"); var $trNew = $trLast.clone(); 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 () { // 更新输入框name属性的索引 var oldName = $(this).attr('name'); var newName = oldName.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']'); $(this).attr('name', newName); // 仅清空非Email文本输入框 if ($(this).attr('type').toLowerCase() === "text") { if ($(this).hasClass("email-input")) { $(this).val(loggedInEmail); } else { $(this).val(''); } } $(this).removeClass("input-validation-error"); }); $trLast.after($trNew); // 重新绑定表单验证 var form = $("form") .removeData("validator") .removeData("unobtrusiveValidation"); $.validator.unobtrusive.parse(form); }); // 删除行 $(document).on('click', '.remove', function () { $(this).closest('tr').remove(); }); });
关键说明
- 通过
$(".email-input").first().val()获取初始登录用户的Email值并存储,确保所有新行都继承该值。 - 使用
hasClass("email-input")区分Email输入框,避免被清空,而是赋值为存储的初始值。 - 移除重复ID,改用class选择器操作,符合HTML规范,避免潜在的选择器冲突。
内容的提问来源于stack exchange,提问作者Rezo
相关产品推荐
相关产品推荐

