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