0

I have two select tags in my page. Each of these have several options within. Now I want to access only the second select box, but since I have used getElementByTagName("options") so it is fetching only the first option tag.I am unable to access the second option tags.

My code is here:

function myFunction() {
  var x = document.getElementById("mySelect_two").selectedIndex;
  alert(document.getElementsByTagName("option")[x].value); 
}
<!DOCTYPE html>
<html>
  <body>

  Select your favorite fruit:
  <select id="mySelect_one">
    <option value="apple">Apple</option>
    <option value="orange">Orange</option>
    <option value="pineapple">Pineapple</option>
    <option value="banana">Banana</option>
  </select>

  <select id="mySelect_two">
    <option value="India">India</option>
    <option value="Nepal">Nepal</option>
    <option value="Spain">Spain</option>
    <option value="Mexico">Mexico</option>
  </select>

  <p>Click the button to return the value of the selected fruit.</p>

  <button type="button" onclick="myFunction()">Try it</button>

  </body>
</html>
Samuel Bolduc
  • 18,163
  • 7
  • 34
  • 55
Abhradip
  • 393
  • 5
  • 27
  • So select the options of the select, not the entire document. – epascarello Jul 07 '16 at 13:54
  • how to do this? actually in my code I have mentioned getElementById("mySelect_two") but it is still fetching the options from select with id "mySelect_one" – Abhradip Jul 07 '16 at 13:55
  • so you already selected the element to get the index, do the same thing to get the options. – epascarello Jul 07 '16 at 13:56
  • – Sunil Kumar Jul 07 '16 at 14:08

3 Answers3

1

you need to get elements by tag name on the select rather than entire document

function myFunction() 
{
    var select = document.getElementById("mySelect_two");
    var x = select.selectedIndex;
    alert(select.getElementsByTagName("option")[x].value); 
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

with options

var sel = document.getElementById("mySelect_two");
var selectedIndex = sel.selectedIndex;
var value = sel.options[selectedIndex].value;

with getElementsByTagName

var sel = document.getElementById("mySelect_two");
var selectedIndex = sel.selectedIndex;
var value = sel.getElementsByTagName("option")[selectedIndex].value;
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Use below script to get selected options value:

var e = document.getElementById("mySelect_two");
var str = e.options[e.selectedIndex].value;
alert(str)
<select id="mySelect_two">
<option value="India">India</option>
<option value="Nepal" selected>Nepal</option>
<option value="Spain">Spain</option>
<option value="Mexico">Mexico</option>
</select>
Jayesh Chitroda
  • 4,987
  • 13
  • 18
  • sorry it is not working...You did not get my question. I asked it makes problem with multiple same tag name – Abhradip Jul 07 '16 at 14:07