How would I set values of a picklist with Javascript? Like for example, a page loads, and I want several values of a picklist to be selected (I will generate these with PHP from the database and echo the actual Javascript). I don't need the actual page load part, just how to select a value out of a picklist (with multiple select)
            Asked
            
        
        
            Active
            
        
            Viewed 2,437 times
        
    1
            
            
        - 
                    1Why don't you mark them as selected right within PHP, when you create the page? – Tomalak Nov 28 '11 at 17:18
- 
                    Check this question http://stackoverflow.com/questions/149573/check-if-option-is-selected-with-jquery-if-not-select-a-default – Toni Toni Chopper Nov 28 '11 at 17:21
- 
                    @JakeSmith You add a `selected` attribute to every ` – Tomalak Nov 28 '11 at 17:27
1 Answers
4
            
            
        A select contains an options collection.  Each element therein has a selected property.  To select certain items in your select, just use a simple loop and set selected to true for the desired options: 
<select id="multiPickList" multiple="multiple">
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
    <option value="5">E</option>
</select>
<script type="text/javascript">
    var pl = document.getElementById("multiPickList");
    for (i = 0; i < pl.options.length; i++) {
       if (i % 2 == 0) {
          pl.options[i].selected = true;
       }
    }
</script>
 
    
    
        Hossein
        
- 4,097
- 2
- 24
- 46
 
    
    
        Adam Rackis
        
- 82,527
- 56
- 270
- 393
 
    