jQuery Multiselect自动选择

时间:2012-06-25 03:52:34

标签: jquery multi-select

我在某个时候有这个工作,因为我过去对此有一个问题帮助了我,但现在我丢失了代码,所以我回到我的问题并尝试让它工作,现在它不是“T ...

请有人帮我解释为什么这不再适用了?

CODE

var valArr = [3, 4];
size = valArr.length;
for (i = 0; i < size; i++) {
    $("#secondary_group option[value='" + valArr[i] + "']").
                                            attr("selected", 1);
    $("#secondary_group").multiselect("refresh");
}

演示: http://jsfiddle.net/VXbLE/

它应该做什么,是根据它的值选择选项,基本上,你可以从jsfiddle中读取代码并想出来。

我是JavaScript / jQuery的初学者,所以我完全不理解它......

1 个答案:

答案 0 :(得分:1)

var valArr = [3, 4];
size = valArr.length; // detect array length
// looping over array
for (i = 0; i < size; i++) {

    // $("#secondary_group option[value='" + valArr[i] + "']")
    // select the option with value match with the valArr
    // from the select with id=secondary_group and if match found
    // .attr("selected", 1);  make that option as default selected

    $("#secondary_group option[value='" + valArr[i] + "']")
                                            .attr("selected", 1);
}

// after selecting the options
// refresh the select using below code
// And this code should belong outside of
// above loop, because
// refreshing within loop will only 
// select last matched element
// not all matched

$("#secondary_group").multiselect("refresh");

DEMO