Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript select element

Tags:

javascript

I have a select element like this

<select name ="cars">
  <option value="frd"> Ford </option>
  <option value="hdn"> Holden </option>
  <option value="nsn"> Nissan </option>
</select>

I want to set selected to "Holden" with javascript without selected by value. how can I achieve this?

Thanks in advance

like image 942
qwera Avatar asked Jan 20 '23 16:01

qwera


1 Answers

update after comment

Use the following to find the option by text and select it

var optionlist = document.getElementById('cars').options;

for (var option = 0; option < optionlist.length; option++ )
{
  if (optionlist[option].text == 'Holden')
  {
    optionlist[option].selected = true;
    break;
  }
}

demo at http://jsfiddle.net/gaby/vQhfq/


original

When there is no value attribute specified for option elements, they assume the value to be the text.

I would suggest you use an id, so you can easily find the element.

Html

<select name ="cars" id="cars">
  <option> Ford </option>
  <option> Holden </option>
  <option> Nissan </option>
</select>

javascript

document.getElementById('cars').value = 'Holden';

(make sure you run this code, after the select element is created)

demo at http://jsfiddle.net/gaby/Pwb5u/

like image 83
Gabriele Petrioli Avatar answered Jan 31 '23 01:01

Gabriele Petrioli