Search code examples
javascripthtml-selectuserscripts

How to select multiple <option> values with a userscript?


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

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