将下拉列表设置为多个值的语法如下:
$("#multiple").val(["Multiple2", "Multiple3"]);
我的问题是我不知道我有多少价值观。那么如何使用数组中的值动态地将下拉列表设置为多个值?
答案 0 :(得分:3)
您的代码应该如此live demo中所示。
标记:
<select multiple="multiple" id="multiple">
<option value="1">item 1</option>
<option value="2">item 2</option>
</select>
脚本:
$('#multiple').val(['1', '2']);
结果:
答案 1 :(得分:0)
检查数组是否有更多值:
if (array[i]) { //DO WHAT YOU NEED}
答案 2 :(得分:0)
我不清楚你想要实现的目标。 您可以使用数组作为val()和this is the result的参数:
> Passing an array of element values allows matching <input
> type="checkbox">, <input type="radio"> and <option>s inside of n
> <select multiple="multiple"> to be selected. In the case of <input
> type="radio">s that are part of a radio group and <select
> multiple="multiple"> the other elements will be deselected.
这意味着在您的情况下只会影响启用了多选项的选项(而不是简单的下拉列表)。
相反,如果“设置为多个值”意味着向现有选择添加选项,则不会构建val()(为此,您可以a look here)