0

hi all,

I have a html code like
<select id="search">
<option id="21" value="internal">
.
.
.

using document.getelementbyId("search").value
i get internal but i need to get id of internal..

how can i do that help me..

3
Contributors
2
Replies
4
Views
7 Years
Discussion Span
Last Post by Airshow
0

I'm not entirely sure on what you're trying to achieve here but hopefully this may help.

//the reason why you get internal is because of the .value
document.getelementbyId("search").value 

//to get the first option do this
document.getElementById("search").options[0]

//if you want to get the ID of the first option do this
document.getElementById("search").getElementsByTagName('option')[0].id; //this should return 21

Edited by qazplm114477: n/a

0

Anandhikrishnan,

What Qazplm says or more conventially:

var el = document.getElementById("search");
var id = (el && el.options.length) ? el[el.selectedIndex].id : null;

For the record (and if I recall correctly) obtaining value directly with selectElement.value is problematic in that some browser(s)/version(s) return 'undefined'.

A safer way to get value is a slight modification of the code above for id:

var el = document.getElementById("search");
var id = (el && el.options.length) ? el[el.selectedIndex].value : null;

In both cases, null is returned if the select element does not exist or if it has no options.

Airshow

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.