0

I have the following drop down list:

<select name="selSS1" id="select_value">
    <option value="val0">sea zero</option>
    <option value="val1">sea one</option>
    <option value="val2">sea two</option>
    <option value="val3">sea three</option>
    <option value="val4">sea four</option>
</select>

I would like to dynamically select a value from that list using javascript:

I tried:

document.getElementById('select_value').selected ="val3";

But the above code does not seem to work. Any help is most appreciated.

Kim
  • 2,070
  • 5
  • 33
  • 46

7 Answers7

6

Use the following line:

 document.getElementById('select_value').value ="val3";

or 

    document.getElementById('select_value').selectedIndex = 3;

Hope this solves ur problem.

AmGates
  • 2,127
  • 16
  • 29
1

try:

var mySelect = document.getElementById('select_value');
mySelect.getElementsByTagName('option')[index].setAttribute('selected','selected');

where index stands for the position of the option you want to select.

Code Maverick
  • 20,171
  • 12
  • 62
  • 114
Th0rndike
  • 3,406
  • 3
  • 22
  • 42
1
$('#select_value').val('val0');
John Leehey
  • 22,052
  • 8
  • 61
  • 88
Pratik Bhatt
  • 871
  • 1
  • 8
  • 21
0

With plain JavaScript:

var element = document.getElementById("select_value");
var selectedValue = element.options[element.selectedIndex].value;
Bogdan Emil Mariesan
  • 5,529
  • 2
  • 33
  • 57
0

Try it this way:

document.getElementById('select_value').option[3].selected;

Rafael Marques
  • 797
  • 1
  • 8
  • 18
0

THis will select val 3

document.getElementById('select_value').selectedIndex=3;
Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59
0

If you want to set the selected one by the value, try this function. By declaring a function you will be able to use this functionality with any select :).

// Simplest version

function setSelected(select_id,value){

    document.getElementById(select_id).value = value;

}

// Or, complex version

function setSelected(select_id,value){

    var mySelect = document.getElementById(select_id);
    var options = mySelect.options;
    var key;
    for(key in options){

        if(options[key].value===value){
            options[key].setAttribute("selected","");
        }
        else
            options[key].removeAttribute("selected");
    }
}

in your case:

setSelected("select_value","val3");
Javier Cobos
  • 1,172
  • 10
  • 22