You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery获取DataTable每行select下拉框的选中选项值

问题解决方法

核心原因

  • HTML规范要求id属性必须全局唯一,重复id会导致DOM选择器只会匹配到第一个对应id的元素,这是你拿不到每行独立选中值的根本原因
  • 原JS代码中全局匹配select[name=agentList]没有限定范围,每次取的都是整个页面第一个下拉框的选中值

第一步:修改HTML代码

你可以用每行客户数据的唯一标识拼接出动态id,也可以直接保留class标识用于后续选择(不需要依赖id也能实现取值):

@foreach (var customer in Model.customerLoadList)
{
<!-- 去掉重复的tr id,或者用客户id拼接成动态id,比如id="customerRow_@customer.CustomerId" -->
<tr class="customerRow">
    <td>@customer.Name</td>
    <td>@customer.Surname</td>
    <td>@customer.PhoneNumber</td>
   
    <td class="agentList">
    <div class="form-group">
    <!-- 动态拼接id,保留原有的agentSelect类 -->
    <select id="agentList_@customer.CustomerId" name="agentList" class="agentSelect form-control">
     @foreach (var agent in Model.agentList)
     {
      <option value="@agent.AgentId">@agent.AgentNameSurname</option>
      }
    </select>
    </div>
    </td>
</tr>}

如果你的customer没有CustomerId这类唯一字段,也可以用循环索引拼接:

@{ var index = 0; }
@foreach (var customer in Model.customerLoadList)
{
    <tr>
        <!-- 其他字段不变 -->
        <select id="agentList_@index" name="agentList" class="agentSelect form-control">
        <!-- 下拉选项不变 -->
        </select>
    </tr>
    index++;
}

第二步:修改jQuery取值逻辑

遍历每一行的时候,限定在当前行范围内查找下拉框的选中值即可,同时推荐用DataTable内置的遍历方法,避免分页、过滤时漏拿数据:

function SaveCustomer() {
    var customerListForAdd = [];
    // 用DataTable内置方法遍历所有行(包含隐藏的分页行)
    $('.data-table-customer').DataTable().rows().every(function (rowIdx) {
        // 拿到当前行的DOM节点
        var currentRow = this.node();
        var customerObj = {
            Name: this.cell(rowIdx, 0).data().toString(),
            Surname: this.cell(rowIdx, 1).data().toString(),
            PhoneNumber: this.cell(rowIdx, 2).data().toString(),
            // 仅在当前行范围内查找下拉框的选中值
            Agent: $(currentRow).find('select.agentSelect').val()
        };
        customerListForAdd.push(customerObj);
    });

    $.ajax({
        type: 'POST',
        url: '/Stock/SaveCustomerList',
        data: { "customerListForAdd": customerListForAdd }, 
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (r) {
            alert(r + " record(s) inserted.");
        }
    });
}

内容的提问来源于stack exchange,提问作者Manizha Rasouli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:45:03