[英]<select> get selected option number
So i have a <select>
with option, but what i want when i select a option to get the option number. 所以我有一个带有选项的
<select>
,但是当我选择一个选项来获取选项编号时我想要什么。
I do not want him to grab attributes(No value & text). 我不希望他获取属性(无值和文本)。 Because it is dynamic.
因为它是动态的。
Example: 例:
<select id="mySelect">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
When i select Apple, that I get a response 1. so with Pear: 2. and so on. 当我选择Apple时,我得到的答复是1.梨子:2。依此类推。
I have found: W3school , But this will show how many option are available. 我发现: W3school ,但这将显示有多少个可用的选项。
What someone here a solution for? 什么人在这里解决?
You can use the selectedIndex
property of the <select>
. 您可以使用
<select>
的selectedIndex
属性。
$("#mySelect").change(function() { console.log("Selected option is " + this.selectedIndex); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="mySelect"> <option>Choose a fruit</option> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select>
$('#mySelect').change(function(){
$(#mySelect option).each(function(index){
if ($(this).attr('selected') {
console.log(index);
}
});
})
You may have to change out .attr() for .prop() depending on your version of Query 您可能必须将.attr()更改为.prop(),具体取决于您的Query版本
May also use 也可以使用
$('#mySelect').change(function(){
$("#mySelect option").index($("#mySelect option:selected"))
})
You could try something like this using plain JavaScript: 您可以使用纯JavaScript尝试类似的方法:
document.addEventListener('DOMContentLoaded', function(){ var selectEle = document.getElementById('mySelect'); selectEle.addEventListener('change', function(item){ console.log(selectEle.selectedIndex + 1); }); });
<select id="mySelect"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.