javascript 在页面加载时选择具有多个选定值的选择框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19520032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:51:55  来源:igfitidea点击:

Chosen select box with multiple selected values on page load

javascriptjqueryselectjquery-chosen

提问by Digital fortress

I'm trying to select multiple values on page load, but it only selects the last value on the array. Take a look at the code

我试图在页面加载时选择多个值,但它只选择数组中的最后一个值。看一下代码

jQuery("#language").chosen();
var str = '12,24,36';
var languageArray = str.split(',');
 for (var i = 0; i < languageArray.length; i++) {
     jQuery("#language").val(languageArray[i]);
     jQuery("#language").trigger("liszt:updated");
 }

I get only 36 selected on page load, is there anything wrong with the js ?

我在页面加载时只选择了 36 个,js 有什么问题吗?

Here is the HTML for the select

这是选择的 HTML

<select name="language[]" id="language" data-placeholder="Choose Language..."  multiple="multiple">

I appreciate your help.

我感谢您的帮助。

Thanks

谢谢

回答by Eiríkur Fannar Torfason

You can select multiple options in a multi-value select box by passing an array to the val()method.

通过将数组传递给val()方法,您可以在多值选择框中选择多个选项。

Example

例子

Markup

标记

<select name="language" id="language" data-placeholder="Choose Language..."  multiple="multiple">
    <option value="en">English</option>
    <option value="fr">French</option>
    <option value="de">German</option>
</select>

JavaScript

JavaScript

var str = 'en,de';
jQuery("#language").val(str.split(','));

And here's a jsFiddlefor funsies.

这里有一个jsFiddle的 funsies。

回答by Sheldon

you could set the selectedproperty of matched option element. hope it would help.

您可以设置selected匹配选项元素的属性。希望它会有所帮助。

var values = ['1', '2', '4'];
$('#languages').find('option').filter(function (idx, option) {
    if($.inArray(option.value, values) !== -1) {
        return option;
    }
}).prop('selected', 'true');