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


当前回答

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

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

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

其他回答

如果使用PHP,您可以尝试这样做:

$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';

switch($value) {
            case '10' :
                $first = 'selected';
            break;
            case '11' :
                $second = 'selected';
            break;
            case '14' :
                $third = 'selected';
            break;
            case '17' :
                $fourth = 'selected';
            break;
        }

echo'
<select id="leaveCode" name="leaveCode">
  <option value="10" '. $first .'>Annual Leave</option>
  <option value="11" '. $second .'>Medical Leave</option>
  <option value="14" '. $third .'>Long Service</option>
  <option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';

你很可能想要这个:

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

OR

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

你可以使用这个函数:

函数selectElement(id, valueToSelect) { let element = document.getElementById(id); 元素。value = valueToSelect; } selectElement(‘leaveCode’,‘11’); <select id="leaveCode" name="leaveCode"> <option value="10">年假</option> . <option value="11">病假</option> . <option value="14">长业务</option> . <option value="17">无薪休假</option> < /选择>

如果你也想触发onchange事件,你可以使用:

element.dispatchEvent(new Event('change'))

为什么不为元素的Id添加一个变量,使其成为一个可重用的函数呢?

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

我比较了不同的方法:

JS和jQuery设置select值的不同方法比较

代码:

$(function() {
    var oldT = new Date().getTime();
     var element = document.getElementById('myId');
    element.value = 4;
    console.error(new Date().getTime() - oldT);

    oldT = new Date().getTime();
    $("#myId option").filter(function() {
        return $(this).attr('value') == 4;
    }).attr('selected', true);
    console.error(new Date().getTime() - oldT);

    oldT = new Date().getTime();
    $("#myId").val("4");
    console.error(new Date().getTime() - oldT);
});

在有~4000个元素的选择上输出:

1毫秒 58岁的女士 612毫秒

Firefox 10。注意:我做这个测试的唯一原因,是因为jQuery在我们的列表中有~2000个条目时表现非常糟糕(选项之间的文本更长)。 在val()之后,我们有大约2秒的延迟。

还要注意:我设置的值取决于实际值,而不是文本值。