hot以获取所选文本,并在select中选择索引

hot to get the selected text and selectedIndex in select?

本文关键字:select 并在 选择 索引 文本 获取 hot      更新时间:2023-09-26

我需要在提交时在下拉列表中获取所选文本和selectedIndex。。下面的代码返回第一个索引,第一个选项文本始终为0。。例如,如果我选择了三个,它显示0个索引和一个文本。。。

function myfunc()
 {
    `enter code here`var x = document.getElementById("listt").selectedIndex;
    var y = document.getElementById("listt").options;
    alert("Index: " + y[x].index + " is " + y[x].text);
}
 <select id="listt" >
   <option >one</option>
    <option >two</option>
     <option>three</option>
     <option >four</option>
    </select>
<input type="Submit" value="submit " name="Submit" onclick="myfunc()"></input>

试试这个代码。

<select id="listt" >
    <option >one</option>
    <option >two</option>
    <option>three</option>
    <option >four</option>
</select>
<input id="btnSubmit" type="Submit" value="submit " name="Submit" />

function myfunc() {
    var x = document.getElementById("listt").selectedIndex;
    var y = document.getElementById("listt").options;
    alert("Index: " + y[x].index + " is " + y[x].text);
}
document.getElementById ("btnSubmit").addEventListener ("click", myfunc, false);
相关文章: