Reputation:
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.
Upvotes: 32
Views: 55674
Reputation: 1221
try this...
document.observe('dom:loaded', function() {
$('mySelect').observe('change', function(event) {
...
});
});
Upvotes: -1
Reputation: 99
Try this:
$('mySelect').setValue(1); // or whatever value you want to select
this one would select option1
Upvotes: 9
Reputation: 21
Assuming you know what value you want to be selected, try:
$('mySelect').value = 2; // 2 being the value you want selected
Upvotes: 1
Reputation: 11
var itis = $(mySelectId).select('option[value="' + sValueToSelect + '"]');
if ( itis && itis.length > 0 )
itis[0].selected = true;
Upvotes: 1
Reputation: 11
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;
});
Upvotes: 1
Reputation: 91
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
}
});
Upvotes: 8
Reputation: 2417
var selectThis = 'option1';
$$('select#mySelect option').each(function(o){
if(o.id==selectThis){o.selected = true;$break;}
});
Upvotes: 0
Reputation: 6540
To get the currently selected option, use:
$$('#mySelect option').find(function(ele){return !!ele.selected})
Upvotes: 15
Reputation: 70424
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;
Upvotes: 34