如何使用javascript或jQuery快速选择预设的多选列表框项? [英] How to use javascript or jQuery to quickly select a preset of multi-select listbox items?

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

问题描述

所以说我的页面有一个索引列表'1,3,4,5,9,12'和一个包含12个项目的多选列表框。

So say my page has a list of indexes '1,3,4,5,9,12' and a multi-select listbox with 12 items in it.

使用javascript告诉列表框多选这些索引中的所有项目有什么快捷的方法?

What's a fast way to use javascript to tell the listbox to multi-select all items at those indexes?

如何使用jQuery完成这项工作?

How would this be done using jQuery?

例如,如果用户选择与'candybar'列表框关联的'焦糖'预设,它将选择所有焦糖的糖果棒...我想你明白了。

So for example if the user selects the 'caramel' preset associated with the 'candybar' listbox, it will select all the candy bars that have caramel... I think you get the idea.

推荐答案

这可以解决问题:

<select id="select" multiple="multiple">
    <option value="1">test 1</option>
    <option value="2">test 2</option>
    <option value="3">test 3</option>
    <option value="4">test 4</option>
    <option value="5">test 5</option>
    <option value="6">test 6</option>
    <option value="7">test 7</option>
    <option value="8">test 8</option>
    <option value="9">test 9</option>
    <option value="10">test 10</option>
    <option value="11">test 11</option>
    <option value="12">test 12</option>
</select>

Javascript(jQuery):

Javascript (jQuery):

indexes = [1,3,4,5,9,12]
$(document).ready(function(){
    for(i=0; i<indexes.length; i++){
        $('#select option:eq(' + (indexes[i]-1) + ')').attr('selected', 'selected');
    }
});

没有jQuery:

window.onload = function(){
    var indexes = [1,3,4,5,9,12];
    var options = document.getElementById('select').options;
    for(i=0; i<indexes.length; i++){
        options[indexes[i]-1].selected = true;
    }
}

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

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