Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected option ID with Javascript not JQuery

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>
like image 666
yorgos Avatar asked Sep 27 '12 16:09

yorgos


People also ask

How do I get the selected option ID?

Getting the selected ID using the selectedIndex and options properties # The options property returns an HTMLOptionsCollection , an array-like collection of options for a select element. You can pair it with the selectedIndex property to get the selected option . Then, you can use the id property to get its ID.

How can check select option selected or not in jQuery?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How do I give an ID an option tag?

The id value must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.).


1 Answers

<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

like image 105
Fabrizio Calderan Avatar answered Oct 07 '22 01:10

Fabrizio Calderan