如何使用Javascript而不是JQuery获取选定的ID [英] How to get selected option ID with Javascript not JQuery
问题描述
假设我们有多个选择标记。
$ b我需要用Javascript而不是JQuery来打印选定的选项ID。$ b
< select onchange =showOptions(this)id =my_select1>
< option value =a1id =ida1> Option1< / option>
< option value =a2id =ida2> Option2< / option>
< / select>
< select onchange =showOptions(this)id =my_select2>
< option value =b1id =idb1> Option1< / option>
< option value =b2id =idb2> Option2< / option>
< / select>
我发现以下方法 options [selectedIndex] .id
但是我怎么知道这些线是指哪一个?
有什么建议吗?
< select id =my_selectonchange =showOptions2(本)>
< option value =o1id =id1> Option1< / option>
< option value =o2id =id2> Option2< / option>
< / select>
< script type =text / javascript>
function showOptions2(s){
var adVALUE = console.log(s [s.selectedIndex] .value); //获得值
var adID = console.log(s [s.selectedIndex] .id); //获取ID
alert(adID);
}
< / script>
<选择onchange =showOptions(this)>
...
此功能将做这项工作
$ b $ pre $ lt; code> function showOptions(s){
console.log(s [s.selectedIndex] .value) ; //获取值
console.log(s [s.selectedIndex] .id); //获取id
}
请注意,除非您将它们用于其他目的,您可以省略 select
元素
上的 id
jsbin: http://jsbin.com/adopiz/2/edit
I need to print the selected option ID with Javascript not JQuery for both select tags.
Assume we have more than one select tags.
<select onchange="showOptions(this)" id="my_select1">
<option value="a1" id="ida1">Option1</option>
<option value="a2" id="ida2">Option2</option>
</select>
<select onchange="showOptions(this)" id="my_select2">
<option value="b1" id="idb1">Option1</option>
<option value="b2" id="idb2">Option2</option>
</select>
I found out the following way options[selectedIndex].id
but how can I know to which one of those that line refers to..
Any suggestions?
I Tried the following but it did not work.
<select id="my_select" onchange="showOptions2(this)">
<option value="o1" id="id1">Option1</option>
<option value="o2" id="id2">Option2</option>
</select>
<script type = "text/javascript">
function showOptions2(s){
var adVALUE = console.log(s[s.selectedIndex].value); // get value
var adID = console.log(s[s.selectedIndex].id); // get id
alert(adID);
}
</script>
<select onchange="showOptions(this)">
...
this function will do the work
function showOptions(s) {
console.log(s[s.selectedIndex].value); // get value
console.log(s[s.selectedIndex].id); // get id
}
Note that, unless you are using them for other purpose, you may omit the id
on select
elements
Example jsbin : http://jsbin.com/adopiz/2/edit
这篇关于如何使用Javascript而不是JQuery获取选定的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!