2012-03-06 102 views
5

语法的下拉列表设置为多个值如下:如何将dropdownlist设置为多个值?

$("#multiple").val(["Multiple2", "Multiple3"]); 

我的问题是,我不知道有多少价值有。那么如何使用数组中的值将下拉列表动态设置为多个值?

+1

你可以建立你所有的值的数组,并将其传递到'VAL (..)'? – 2012-03-06 12:19:32

+1

@Royi Namir:您可以设置属性multiple =“multiple”。 – Luke 2012-03-06 12:21:22

+0

@RoyiNamir,因为总是:http://www.w3.org/TR/html4/interact/forms.html#adef-multiple – 2012-03-06 12:22:52

回答

0

做检查,以了解如果数组有多个值:

 if (array[i]) { //DO WHAT YOU NEED} 
+0

此语句不检查数组中的多个值... – mamoo 2012-03-06 12:27:34

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. 

这意味着,将在你的情况下,只有一个选择启用muptiple选择(而不是一个简单的下拉列表)的影响。

如果通过“设置为多个值”方法添加选项,以现有的select,VAL()未建做相反(为此,你可以有a look here

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']); 

结果:

enter image description here

+0

它看起来更像是我的评论,所以我将它标记为不是答案。没有看到它是一个小提琴。我觉得很蠢....对不起,希望你不介意 – Starx 2012-03-06 12:30:46

+0

@Starx,希望管理员在删除它之前会更仔细地阅读答案。 – 2012-03-06 12:36:47

相关问题