views:

5731

answers:

5

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.

+1  A: 
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;
RaYell
So basically it's $("option1").selected = true, right?
If you have id's for your all options set then yes, you can do it like that.
RaYell
Thanks, then I'll do this.
A: 
var selectThis = 'option1';
$$('select#mySelect option').each(function(o){
      if(o.id==selectThis){o.selected = true;$break;}
});
nils petersohn
+1  A: 

To get the currently selected option, use:

$$('#mySelect option').find(function(ele){return !!ele.selected})
DavidWinterbottom
+1  A: 

nils petersohn almost got it right, but typically, the option's "id" attribute is not what people are selecting against. this small change makes it work.

var selectThis = 'option1';
$$('select#mySelectId option').each(function(o) {
  if(o.readAttribute('value') == selectThis) { // note, this compares strings
    o.selected = true;
    throw $break; // remove this if it's a multi-select
  }
});
Chaz Meister Rock