Question

I currently use the following javascript to select an element from the HTML below. How can I select multiple values at the same time?

Script:

//Select Forum
var forumselector = document.querySelector('select#forumchoice');
forumselector.value = 326;

HTML:

<select class="primary" id="forumchoice" name="forumchoice[]" multiple="multiple" tabindex="1" size="5">                        
<option value="" class="" selected="selected">Search All Open Forums</option>
<option value="subscribed" class="" >Search Subscribed Forums</option>
<option value="130" class="d0" > The Community</option>
<option value="327" class="d1" > General Support</option>
<option value="326" class="d2" > Beginners Section</option>
<option value="331" class="d2" > General Help</option>
...
Était-ce utile?

La solution

You can use document.querySelectorAll and iterate through the nodelist:

var forumselector = document.querySelectorAll('select#forumchoice option');

for (var i = 0; i < forumselector.length; i++) {
    if (['327', '331'].indexOf(forumselector[i].value) != -1) {
        forumselector[i].setAttribute('selected', 'selected');
    }

}

Demo

Autres conseils

If want to select multiple values through same select box then try this

<select multiple="multiple">

If wanted to select multiple element using javascript then try Use comma separated elements.

document.querySelectorAll('select#selectEleId, #eleId2');

Hope this helps...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top