1

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)

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Ryan Schafer
  • 245
  • 2
  • 9
  • 16

1 Answers1

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