在多个选择列表中设置所选值

时间:2013-03-04 02:04:29

标签: javascript jquery html

我有这个多选列表:

<select id="vendors" name="vendors" multiple="multiple">
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
    <option value="5">E</option>
</select>

当页面加载时,我正在加载需要在我的选择列表中选择的ID列表。以下是我试图这样做的方法:

var vendors = GetVendorArray();  // list of vendor ids I want selected

$.each(vendors, function(index, item) {
    $("#vendors").filter(function() {
        return $(this).val() == item; 
    }).attr('selected', true);
});

但是这不起作用,没有选择任何项目。谁知道我做错了什么?

2 个答案:

答案 0 :(得分:4)

最简单的方法是使用select将整个数组作为值传递给val()mulitple select值是一个数组

$('#vendors').val(  GetVendorArray())

样本:http://jsfiddle.net/sPKAY/

您采用的方法问题不是循环option标记

答案 1 :(得分:1)

filter减少匹配元素的集合以匹配其他选择器/回调fn。输出。您需要定位<option>元素,而不是下拉列表本身,因为您尝试根据其值是否与数组内容匹配来选择该选项。

var vendors = GetVendorArray();  // list of vendor ids I want selected

$.each(vendors, function(index, item) {

    //you're filtering options, not the list itself
    $("#vendors > option").filter( function() {
        return $(this).val() == item; 
    }).prop('selected', true); //use .prop, not .attr
});
相关问题