views:

5765

answers:

9

I have the following HTML select element:

<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

Using a javascript function with the leave code number as a parameter, how do I select the appropriate option in the list?

+7  A: 
function SelectElement(valueToSelect)
{    
    var element = document.getElementById('leaveCode');
    element.value = valueToSelect;
}
Mitchel Sellers
This is not very cross-browser compatible.
Milan Babuškov
I know that it works in IE, FF, and Safari. Where doesn't it work?
Mitchel Sellers
A: 

Not answering the question, but you can also select by index, where i is the index of the item you wish to select:

var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;

You can also loop through the items to select by display value with a loop:

for (var i = 0, len < formObj.leaveCode.length; i < len; i++) 
    if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
Chase Seibert
A: 

I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:

document.getElementById("optionID").select();

If that doesn't work, maybe it'll get you closer to a solution :P

Lucas Oman
+3  A: 

function foo(value)
{
    var e = document.getElementById('leaveCode');
    if(e) e.value = value;
}

mmattax
+1  A: 
document.getElementById('leaveCode').value = '10';

That should set the selection to "Annual Leave"

William
A: 

Should be something along these lines:

function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (i=0; i<dl.options.length(); i++){
 if (dl.options[i].value == inVal){el=inVal;}
}
dl.selectedIndex = el;
}
Stephen Wrighton
A: 

Why not add a variable for the element's Id and make it a reusable function?

function SelectElement(selectElementId, valueToSelect)
{    
    var element = document.getElementById(selectElementId);
    element.value = valueToSelect;
}
Swish
A: 

Suppose your form is named form1:

function selectValue(val)
{
  var lc = document.form1.leaveCode;
  for (i=0; i&lt;lc.length; i++)
  {
    if (lc.options[i].value == val)
    {
        lc.selectedIndex = i;
        return;
    }
  }
}
Milan Babuškov
A: 
function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Andrew Hedges