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

1 Answer 1

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;
});
Sign up to request clarification or add additional context in comments.

3 Comments

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?
I think you could add a .fire for the $(sel) just before or after sel.selectedIndex = 0;
Okay, finally achieved it from the answer by Greg in this post stackoverflow.com/questions/460644/… . Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.