tags:

views:

158

answers:

2

The following code resets one selectOneMenu through particular id. How to make it dynamic for more selectOneMenus to reset at the top value.

var test= document.getElementById('form1:text3');
 test.options.selectedIndex=0;

This resets to top value of menu, but how to make it dynamic.

ANy help is appreciated.

A: 

I'm sure someone else will mention this... but have you tried jQuery?

jQuery makes selecting DOM elements easy. (And it makes it easy to manipulate them too!)

George Edison
thnks for the reply but I am not using Jquery. I just want to iterate through all selectone menu and setto default.
A: 

So if this is your markup:

<select id="text3">
    <option>Original Item</option>
</select>

This code:

window.onload = function() {
    var test= document.getElementById('text3');
    // this will add 3 option tags as children of the select:
    test.options[test.options.length] = new Option('TextValue','ValueValue');
    test.options[test.options.length] = new Option('TextValue2','ValueValue2');
    test.options[test.options.length] = new Option('TextValue3','ValueValue3');
    // this will select the 2nd option
    test.options.selectedIndex=1;
}

If JavaScript is enabled, then that will be transformed into:

<select id="text3">
    <option>Original Item</option>
    <option value="ValueValue">TextValue</option>
    <option value="ValueValue2">TextValue2</option>
    <option value="ValueValue3">TextValue3</option>
</select>

Libraries make this much easier to accomplish, but that will get you started.

Like you said you can use test.options.selectedIndex=1; will be the code you need to set which one is selected. They are zero indexed, so the first one is 0, the second is 1, the third is 2, etc.

artlung
i just want to iterate through all the selectonemenu I have and set all to default. i am using JSF