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

StackOverflow https://stackoverflow.com/questions/2179529

  •  24-09-2019
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top