且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从JavaScript的下拉列表中获取选定的值

更新时间:2023-01-13 19:19:34

对我来说很好.

我有以下HTML:

<div>
    <select id="select1">
        <option value="1">test1</option>
        <option value="2" selected="selected">test2</option>
        <option value="3">test3</option>
    </select>
    <br/>
    <button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>

以及以下JavaScript:

And the following JavaScript:

function GetSelectedItem(el)
{
    var e = document.getElementById(el);
    var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
    alert(strSel);
}

查看,您正在使用正确的ID.如果您将其与ASP.NET一起使用,则ID在呈现时会更改.

See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.