0

I want to select first option of all the select dropdowns having class required-entry in a page with Prototype JS. I have searched through SO questions and found many relevant questions but not what I exactly needed.

Thanks

Kalpesh
  • 5,635
  • 2
  • 23
  • 39

1 Answers1

1

It's been quite a while since I've done any Prototype.js. So this may not be the best way to go about it, but it should work.

let's say you have a page with:

<select class='required-entry'>
    <option value='a'>AAA</option>
    <option value='b'>BBB</option>
    <option​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ value='c'>CCC</option>
</select>

<select class='required-entry'>
    <option value='x'>XXX</option>
    <option value='y'>YYY</option>
    <option value='z'>ZZZ</option>
</select>​

You can grab the first option for each select by doing:

var firstOptions = [];

$$('.required-entry').each(function(sel, i) {
    firstOptions.push($(sel).getElementsBySelector('option')[0]);
});

// firstOptions is now an array containing the first options

Now, I couldn't tell from your question if you wanted to retrieve the first options, or set the select value so that the first option is literally selected. Here's the later:

$$('.required-entry').each(function(sel, i) {
    sel.selectedIndex = 0;
});
Marshall
  • 4,716
  • 1
  • 19
  • 14
  • Yes I wanted to literally select the first option. Your script even selects the first option, but the function which should be triggered on change event is not getting called. Any ideas? – Kalpesh Aug 01 '12 at 20:36
  • I think you could add a `.fire` for the `$(sel)` just before or after `sel.selectedIndex = 0;` – Marshall Aug 01 '12 at 20:58
  • Okay, finally achieved it from the answer by Greg in this post http://stackoverflow.com/questions/460644/trigger-an-event-with-prototype . Thanks – Kalpesh Aug 01 '12 at 21:34