Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any fast way to get an <option> from a <select> by value, using JavaScript?

I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option. The option may or may not be selected.

Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes).

Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.

like image 790
Max Kanat-Alexander Avatar asked Jan 25 '23 00:01

Max Kanat-Alexander


1 Answers

I'd do it like this:

// first, build a reverse lookup
var optCount      = mySelect.options.length;
var reverseLookup = {};
for (var i = 0; i < optCount; i++)
{
  var option = mySelect.options[i];
  if (!reverseLookup[option.value])
  {
    // use an array to account for multiple options with the same value
    reverseLookup[option.value] = [];
  }
  // store a reference to the DOM element
  reverseLookup[option.value].push(option);
}

// then, use it to find the option
var foundOptions = reverseLookup["Value that you are looking for"];
if (foundOptions && foundOptions.length)
{
  alert(foundOptions[0].id);
}
like image 129
Tomalak Avatar answered Jan 30 '23 02:01

Tomalak