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)

3
  • 1
    Why don't you mark them as selected right within PHP, when you create the page? Commented Nov 28, 2011 at 17:18
  • Check this question stackoverflow.com/questions/149573/… Commented Nov 28, 2011 at 17:21
  • @JakeSmith You add a selected attribute to every <option> that should be selected. No JavaScript needed at all. Commented Nov 28, 2011 at 17:27

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.