Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Always select first option

Status
Not open for further replies.

leonk09

Technical User
Nov 9, 2005
20
GB
I am using a script to populate dropdown menus:

<SCRIPT LANGUAGE="JavaScript">

function SelectSubCat(){
// ON selection of category this function will work

removeAllOptions(document.main.SubCat);

if(document.main.Category.value == '1'){
addOption(document.main.SubGift,"option 1", "option 1");
addOption(document.main.SubGift,"option 2", "option 2");
}
if(document.main.Category.value == '3'){
addOption(document.main.SubGift,"option 1", "option 1");
addOption(document.main.SubGift,"option 2", "toption 2");
}
if(document.main.Category.value == '4'){
addOption(document.main.SubGift,"option 1", "option 1");
}

}
//////////////////

function removeAllOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
//selectbox.options.remove(i);
selectbox.remove(i);
}
}


function addOption(selectbox, value, text )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;

selectbox.options.add(optn);
}

</script>

How can I modify this script so that the first option is automatically selected from my second dropdown menu?

Many thanks and merry Christmas!
 
[1] Maybe a typo, either change to SubGift or else below change to SubCat.
>[tt]removeAllOptions(document.main.SubCat);
removeAllOptions(document.main.Sub[red]Gift[/red]);[/tt]

[2] RemoveAllOptions() can be simplied.
[tt]
function removeAllOptions(selectbox) {
selectbox.options.length=0;
}
[/tt]
[3] To make first option selected, which normally does automatically, add the line to the end of SelectSubCat() function.
[tt] document.main.SubGift.selectedIndex=0;
[/tt]
 
Thanks tsuji, I changed those two things, and it does select the first option in the browser. However...it doesn't seem to work as when the form is submitted the fields are still blank.

(btw, the 'sub.cat' was a typo, I'm actually using one dropdown menu to populate two more menus which is why it got mixed up).

Here's the page I am working on:
I have validation on the 'country' field which is one of the menus that is populated after the first field is selected.

Thanks again
 
PLEASE IGNORE LAST POST

Was a mistake in my coding, fixed now.

Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top