如何使用 jQuery 在多选列表中选择选项? [英] How to select options in Multiple select list with jQuery?

查看:25
本文介绍了如何使用 jQuery 在多选列表中选择选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个下拉菜单.当用户从我想要的第二个(具有多选选项)中的第一个值中选择一个值时,使用 jQuery 自动选择一些值.我该怎么做?

I have two dropdowns. When a user selects a value from the first one I want in the second (which has the multiple select option), with jQuery, to select some values automatically. How can I do that?

First select box:
<select id="update_carte_s" name="update_carte_s">
     <option value="5!**8,9**!6!44.9">Ghid complet Internet</option>
     <option value="6!**6,7**!6!24.95">PC pas cu pas</option>
     <option value="7!**10**!3!27.95">Jocul ingerului</option>
     <option value="8!**11,12**!8!39">Ghidul vinurilor</option>
</select>
Second select box:
<select id="uc_autori_s" name="uc_autorilist[]" size="5" multiple>
     <option value="3">Rose Tremain</option>
     <option value="4">Jonathan Coe</option>           
     <option value="5">Cecilia Ahern</option>
     <option value="6">Marinel Serban</option>
     <option value="7">Emanuela Cherchez</option>
     <option value="8">Peter Buckley</option>
     <option value="9">Clark Duncan</option>
     <option value="10">Carlos-Ruiz Zafon</option>
     <option value="11">Catalin Paduraru</option>
     <option value="12">Dan-Silviu Boerescu</option>
</select>

, 分割的第一个选择框中的粗体值是我想从第二个选择框中选择的值.例如 11,12 表示在第二个框中选择值为 11 和 12 的选项.

The bolded values from the first select box split by , are the values that I want to select from the second select box. For example 11,12 would mean in the second box options with values 11 and 12 to be selected.

目前我有这样的事情:

$.bookAuthors = $.bookDetailsArray[1].split(',');
$.each($.bookAuthors, function( intIndex, objValue ){
      $("#uc_autori_s").val(objValue).attr("selected","selected");
});

但问题是在我的案例 12 中只选择了最后一个值(11 的选择丢失了).

but the problem is that only the last value is selected in my case 12 (selection of 11 is lost).

推荐答案

您将无法使用 val 方法将多个 option 设置为被选中.相反,您应该选择选项本身,并设置其 selected 属性:

You're not going to be able to use the val method to set multiple options as selected. Instead, you should select the option itself, and set its selected attribute:

$('#uc_autori_s option[value=' + objValue + ']').attr('selected', true);

这篇关于如何使用 jQuery 在多选列表中选择选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆