How to use javascript or jQuery to quickly select a preset of multi-select listbox items?

若如初见. 提交于 2019-12-08 09:01:58

问题


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.

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

How would this be done using jQuery?

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.


回答1:


This could do the trick:

<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):

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

Without 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;
    }
}



回答2:


The jquery select plugin has a selectOptions(value[, clear]) method which selects multiple values in a select box. But it takes the values as parameter instead of indexes.




回答3:


You'd be better off setting classes on the option elements and addressing them that way, rather than by index:

<select id="my-select">
  <option class="caramel">Twix</option>
  <option>Mounds</option>
  <option class="caramel">Milky Way</option>
  <!-- ... -->
</select>

And then:

$("option.caramel", "#my-select").each(function () { this.selected = true });

Edit:

But if you really want to do it by index, you could do:

function selectOptionsByIndex(select, indexes) {
    var i = 0;
    select.children().each(function (j) { if (indexes[i] == j) { ++i; this.selected = true } });
}

selectOptionsByIndex($("#my-select"), [ 1, 3, 4, 5, 9, 12 ]);

(This depends on the list of supplied indexes being in ascending order.)



来源:https://stackoverflow.com/questions/2179529/how-to-use-javascript-or-jquery-to-quickly-select-a-preset-of-multi-select-listb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!