我有以下HTML <select>元素:

<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>

使用带有leaveCode数字作为参数的JavaScript函数,我如何在列表中选择适当的选项?


当前回答

假设你的表单名为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;
    }
  }
}

其他回答

应该是这样的:

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

恐怕我现在无法测试这个,但在过去,我相信我必须给每个选项标签一个ID,然后我做了如下的事情:

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

如果这行不通,也许它会让你更接近一个解决方案:P

document.getElementById('leaveCode').value = '10';

这应该会将选择设置为“年假”

假设你的表单名为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;
    }
  }
}
function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);