2

So I currently have a select field that looks something like this:

<select id = "foo">
   <option value = "example">This example</option>
   <option value = "example2">This example Again</option>
   <option value = "bar">This is just a bar</option>
</select>

and if the submitted form returns back with an error, it sends me back all the values in a object, and I need to repopulate the form.

My question: how can I efficiently get the index of value bar, without having to use jQuery?

Is there a way to do it without having to loop through each of the options, checking the value against the one I have, then setting it as checked if it is the same as my value?

Any insight is greatly appreciated

Derek Pollard
  • 6,953
  • 6
  • 39
  • 59

1 Answers1

5

You can combine querySelector() with index:

var selected = document.querySelector( '#foo > option[value="bar"]' );
console.log(selected.index);

jsFiddle Demo

BenM
  • 52,573
  • 26
  • 113
  • 168