2013-01-01 77 views
0

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

// 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”被选中,那么该选择制作并反映在用户界面中。如果只选择“Xbox 360”,则相同。如果应该选择两个选项,我会看到警报声明两者都将被选中,但只有Xbox 360被选中。

回答

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