我有以下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函数,我如何在列表中选择适当的选项?


当前回答

应该是这样的:

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

其他回答

你很可能想要这个:

$("._statusDDL").val('2');

OR

$('select').prop('selectedIndex', 3); 

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

我尝试了上述基于JavaScript/ jquery的解决方案,例如:

$("#leaveCode").val("14");

and

var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;

在AngularJS应用中,有一个必选的<select>元素。

它们都不起作用,因为AngularJS的表单验证没有启动。尽管选择了正确的选项(并显示在表单中),但输入仍然无效(仍然存在ng- primitive和ng-invalid类)。

要强制AngularJS验证,在选择一个选项后调用jQuery change():

$("#leaveCode").val("14").change();

and

var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();

应该是这样的:

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

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