How do I select an option using prototype
54,926
Solution 1
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;
Solution 2
To get the currently selected option, use:
$$('#mySelect option').find(function(ele){return !!ele.selected})
Solution 3
Try this:
$('mySelect').setValue(1); // or whatever value you want to select
this one would select option1
Solution 4
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
}
});
Solution 5
For selecting the second option by value you could use this:
var myChoice = '2';
$$('select#mySelectId option').each(function(o) {
o.selected = o.readAttribute('value') == myChoice;
});
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on August 09, 2020Comments
-
Admin almost 4 years
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.