首页 > 解决方案 > 从表内的下拉列表中获取选定的值

问题描述

现在,我可以从表内下拉列表中的事件 onchange 中获取选定的值,但它仅适用于表的第一行。如果我要更改其他行的值,它仍然会从第一行获取值。

这是我的代码:

<table class="sortable" border="1" id="table">
    <thead>
        <tr>
            <th>Employee Serial</th>
            <th>Grade</th>

        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr style="font-size:11px">
                <td>@item.empSerial</td>

                <td ALIGN="center">
                    <select onchange="getSelValue()" id="drpTechnical" class="testerDrop" style="height:20px; width:100px; text-align-last:center; cursor:pointer">
                        <option value=@item.technicalComp>@item.grade1</option>
                        <option value=@item.empSerial>0</option>
                        <option value=@item.empSerial>1</option>
                        <option value=@item.empSerial>2</option>
                        <option value=@item.empSerial>3</option>
                        <option value=@item.empSerial>4</option>
                    </select>
                </td>                    

            </tr>
        }
    </tbody>
</table>

以及读取所选值的简单脚本:

function getSelValue() {        
        alert(document.getElementById("drpTechnical").value)         
    }

标签: javascripthtml

解决方案


document.getElementById始终只返回具有此 ID 的第一个元素,因为 ID 应该是唯一的。

您想要的是从已更改的元素中获取 id。所以你需要this

function getSelValue(this) {        
    alert(this.value)         
} 

你的桌子应该是这样的

<td ALIGN="center">
  <select onchange="getSelValue(this)" id="drpTechnical" class="testerDrop" style="height:20px; width:100px; text-align-last:center; cursor:pointer">
    <option value=@item.technicalComp>@item.grade1</option>
    <option value=@item.empSerial>0</option>
    <option value=@item.empSerial>1</option>
    <option value=@item.empSerial>2</option>
    <option value=@item.empSerial>3</option>
    <option value=@item.empSerial>4</option>
  </select>
</td>  

推荐阅读