Abhradip Abhradip - 5 months ago 12
jQuery Question

issues related to getElementByTagName

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>




Answer

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); 
}