Frage

Say I have the following select box:

<select id = "cars">
   <option>BMW 320d</option>
   <option>BMW 330d</option>
   <option>BMW 525d</option>
   <option>Mercedes E220</option>
   <option>Peugeot 207</option>
   <option>Peugeot 307</option>
</select>
<input type = "button" id = "selectbmw" value = "Select all BMWs" />

I want a button that selects all cars by BMW; that is, that selects all elements that contain "BMW".

<select id = "cars">
   <option selected>BMW 320d</option>
   <option selected>BMW 330d</option>
   <option selected>BMW 525d</option>
   <option>Mercedes E220</option>
   <option>Peugeot 207</option>
   <option>Peugeot 307</option>
</select>

I thought of doing it as follows:

<script>
   $('#selectbmw').click(function() {
    $('#cars').multiSelect('select', 'contains:"BMW"');
    });
</script>

I am using multiselect.js for this multiselect box. Note that my value field does not contain the name of the car, but an id from the database, so looking up based on value is not an option. I can set an id, name or label attribute to the name of the car if necessary.

War es hilfreich?

Lösung

You need to pass an array of selected values to multiselect, so first create an array of all options which contains BMW using .map()

$('#selectbmw').click(function () {
    var vals = $('#cars option:contains("BMW")').map(function () {
        return this.value
    }).get();
    $('#cars').multiSelect('select', vals);
});

Demo: Fiddle

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top