我有一个用户控件,允许用户输入多个电子邮件收件人。 在页面加载时,我有一个包含名称和电子邮件地址文本框的表格行(没有删除按钮)
使用jQuery添加所有其他表行,因此添加的每行都有一个Remove按钮,允许用户删除特定行。以下是我的代码:
<div>
<table cellspacing="5" runat="server" id="tblEmailRecipients" clientidmode="Static">
<tr>
<td colspan="4">Custom Email Recipients</td>
</tr>
<tr>
<td colspan="3">
<input type="button" value="Add More" onclick="AddNewTableRow();" id="btnAdd" />
</td>
</tr>
<tr style="font-weight:bold">
<td>Name</td>
<td>Email Address</td>
<td></td>
</tr>
<tr>
<td><asp:TextBox runat="server" ID="txtName" ></asp:TextBox> </td>
<td><asp:TextBox runat="server" ID="txtEmailAddress" ></asp:TextBox>
<asp:RegularExpressionValidator ID="regexValidatorEmailAddress" runat="server" ErrorMessage="Invalid Email Address" ControlToValidate="txtEmailAddress"
Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
<td>
<%--<input type="button" value="Remove" onclick="DeleteTableRow(this);" id="btnRemove" name="btnRemove" />--%>
</td>
</tr>
</table>
</div>
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click"
style="height: 26px" />
jQuery的:
function DeleteTableRow(ctrl) {
//delete control table row
$($(ctrl).closest("tr")).remove();
}
function AddNewTableRow() {
//Get Row clone and add as last row
//Also, created row clone but with different control ids
var i = $("#tblEmailRecipients tr").length;
var newRow = $("#tblEmailRecipients tr:last").clone().find("input").each(
function () {
$(this).attr({
'id': function (_, id) { return id + i },
'name': function (_, name) { return name + i },
});
}).end();
$("#tblEmailRecipients tr:last").after(newRow);
$("#tblEmailRecipients tr:last input:text").val("");
//Add 'Remove' button in the last column - this needs to be done only for second row, all rows after 2nd row will auto. contain Remove button as they are cloned from prev. row
var lastCell = $("#tblEmailRecipients tr:last td:last");
var lastCellContents = jQuery.trim($(lastCell).html());
if (lastCellContents == '') {
var btnRemoveName = "btnRemove" + i;
var btnRemove = "<input type='button' value='Remove' onclick='DeleteTableRow(this);' id='" + btnRemoveName + "' name='" + btnRemoveName + "' />";
$(btnRemove).appendTo($(lastCell));
}
//Move focus to newly added row Textbox
$("#tblEmailRecipients tr:last input:first").focus();
}
我面临的问题是在处理btnSave_Click时, 即使我添加了2个或更多收件人(表行),在后面的代码中 - 我只看到包含电子邮件收件人的第一个表行。
我想知道为什么我无法访问在运行时添加的其他表行...在回发后它们也会在UI上丢失?
请你指导。
谢谢!
答案 0 :(得分:0)
尝试为每行的编辑框提供动态ID,你给每行中的所有编辑框都是相同的id。每行的ID应该不同。