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..

Dani AI

Generated

pointed you toward reading option nodes and showed a defensive pattern around the select. Two concise, modern ways to get the id of the selected option without walking options by index:

var chosen = document.querySelector('#search option:checked');
var chosenId = chosen ? chosen.id : null;

For handling change events and multi-selects, use the selectedOptions collection and map to ids (fall back to value if an id is missing):

document.querySelector('#search').addEventListener('change', function(e) {
  var ids = Array.from(e.target.selectedOptions, o => o.id || o.value);
  // single-select: ids[0]
});

Notes and best practice: storing your identifier in the option value or a data-* attribute is usually clearer than relying on option id (IDs must be unique in the document and can complicate CSS selectors). If you use data attributes you can read them with element.dataset. Check browser compatibility for selectedOptions if you must support very old browsers. See the MDN docs for details on querySelector, selectedOptions, and dataset:

Recommended Answers

All 2 Replies

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.