使用 ajax 获取所有行值

To get all the row values using ajax

本文关键字:ajax 获取 使用      更新时间:2023-09-26

在下面的代码中,我有一个包含textboxdropdownlist的表,我可以动态创建新行。

现在我想获取所有行值。 我尝试了以下代码,但它只获取第一行。

$(function () {
    $("#Button1").click(function (event) {
        // Prevents Form Submission as you want to save data via AJAX
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "NewFile.aspx/InsertData",
            data: "{'Quantity':'" + $("#<%=txtQty.ClientID%>").val() + "','ProductID':'" + $("#<%=ddlProduct.ClientID%>").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: "true",
            cache: "false",
            success: function (msg) {
                alert("Success");
                // On success
            },
            Error: function (x, e) {
                alert("Fail");
                // On Error
            }
        });
    });
})
<table id="dataTable" width="350px" border="1" runat="server">
    <tr>
        <td><input id="checkbox" type="checkbox" name="chk" runat="server"/></td>
        <td><input type="text" name="txt" id="txtQty" runat="server"/></td>
        <td>
            <asp:DropDownList ID="ddlProduct" runat="server"  Style="width: 100%; height:23px" ></asp:DropDownList>   
        </td>
    </tr>
</table>   
<asp:Button ID="Button1" Text="Save  New" type="submit" ClientIDMode="Static" runat="server"></asp:Button>

您似乎正在使用 ASP.NET 生成表。 $("#<%=item。ClientID%>")为您提供单个项目。我发现使用 $('[id*="item"]' 来查找在生成的 ASP.NET id 中包含特定文本的对象非常有用。如果所有文本框的 id 中都包含相同的文本,则可以获取如下所示的txtQty值数组:

var values = $('[id*="txtQty"]').map(function(index) {
    return $(this).val(); 
});

您可以类似地找到其他值。

更新

data: { 
         quantites: $('[id*="txtQty"]').map(function() { return $(this).val(); }),
         // ...
}

更新(基于@charlietfl的评论)

var rows = $("#<%=dataTable.ClientID%> tr").map(function() {
    return {
        quantity: $(this).find('[id*="txtQty"]').val(),
        // ...
    };
});