无法使用jquery在SELECT中选择多个OPTIONS

时间:2013-01-01 04:57:09

标签: javascript jquery

我有一个允许多选的HTML select元素。我用ajax请求的结果填充选项。我正在为选项添加自定义属性。在一个实例中,当另一个ajax请求完成时,我想更新多选的值。我有以下javascript方法来做这个选择:

// select = id of the select control.
// selected = list of json objects with an id representing those that are selected.
updateSelection = function( select, selected ) {
    $('#'+select+' option').each( function() {
        var item = $(this);
        $.each(selected, function() {
            item.removeAttr( "selected" );
            if ( this.id === parseInt(item.attr("optionId"), 10 )) {
                alert( "selecting " + item.text());
                item.attr("selected", true );
            }
        });
    });
};

运行该方法之前的HTML如下所示:

<select id="putPlatforms" multiple="multiple">
    <option optionid="1" optionversion="1">PC</option>
    <option optionid="3" optionversion="1">Xbox 360</option>
</select>

在仅选择“PC”的情况下,进行选择并反映在UI中。如果仅选择“Xbox 360”,则相同。如果应该选择BOTH选项,我会看到警告声明两者都将被选中,但只选择了Xbox 360。

1 个答案:

答案 0 :(得分:0)

使用this question的答案,我能够使其发挥作用。我将我的功能改为:

// select = id of the select control.
// selected = list of json objects with an id representing those that are selected.
updateSelection = function( select, selected ) {
    $('#'+select+' option').attr('selected', false );
    $.each(selected, function() {
        $('#'+select+' option[optionid='+this.id+']').attr('selected', true );
    });
};