如何使用jQuery在多个选择列表中选择多个选项? [英] How to select more than one option in multiple selection list using jquery?

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

问题描述

在我的Web应用程序中,一个方法返回一个数组列表,其中包含必须选择的选择选项的ID.很难使用DOM方法将它们全部选中.

In my web application a method returns a list of array contains ID's of select options which should have to be selected. Its is hard to make them all selected using DOM methods.

有什么方法可以使用jQuery.

Is there any way to do it using jQuery.

任何建议都会更加令人感动...

Any suggestions would be more appreciative...

先谢谢了!

推荐答案

编辑:根据下面的注释,您的数据看起来像下面的代码.

Based on your comment below, your data looks the code below.

有问题. HTML ID属性以数字开头无效. ID必须以字母开头.

There's a problem. It is not valid for an HTML ID attribute to start with a number. IDs must begin with a letter.

无论如何,我都会向您显示解决方案,但是您应该修复ID.

I'll show you the solution anyway, but you should fix the IDs.

var array = [{respID:1, respName:null}, 
             {respID:2, respName:null}, 
             {respID:3, respName:null}, 
             {respID:4, respName:null}, 
             {respID:5, respName:null} 
             ];

$.each(array, function(i,val) { 
     $('#' + val.respID).attr("selected", "selected"); 
});

现在,这将为您在循环的每次迭代中提供respID的值.

Now this will give you the value of respID in each iteration of the loop.

但是同样,HTML ID不能以数字开头.我建议将您的HTML ID属性更新为id_5而不是5.

But again, HTML IDs can not start with a number. I'd suggest updating your HTML ID attributes to something like id_5 instead of 5.

<select>
    <option id="id_1" value="some value">some text</option>
    <option id="id_2" value="some value">some text</option>
    <option id="id_3" value="some value">some text</option>
    ...
</select>

然后您将执行以下操作:

Then you would do this:

$.each(array, function(i,val) { 
     $('#id_' + val.respID).attr("selected", "selected"); 
});

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

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