How do I select an option using prototype

lutz picture lutz · Aug 7, 2009 · Viewed 54.3k times · Source

Say I have a HTML form containing this select element:

  <select name="mySelect" id="mySelect">
    <option value="1" id="option1">1</option>
    <option value="2" id="option2">2</option>
  </select>

How can I use prototype to select one of the option elements?

The methods listed in the API reference of Form.Element don't seem to help with this.

edit: by "select" I mean the equivalent effect of the "selected" attribute on an option element.

Answer

RaYell picture RaYell · Aug 7, 2009
var options = $$('select#mySelect option');
var len = options.length;
for (var i = 0; i < len; i++) {
    console.log('Option text = ' + options[i].text);
    console.log('Option value = ' + options[i].value);
}

options is an array of all option elements in #mySelect dropdown. If you want to mark one or more of them as selected just use selected property

// replace 1 with index of an item you want to select
options[1].selected = true;