Friday, September 24, 2004

One selected option selects the option in another select box

I was asked by a colleague if this was possible - so I quickly wrote a javascript function. If you want to go by the value of anoption you will have to amend the code slightly.

<html>
<title>One selected option selects the option in another select box</title>
<head>
<script language="JavaScript">
function setSelectedOption() {
//get the number of the selected option - first option is 0
var selectedOption = document.formName.selectName1.selectedIndex;

//Check that one has been selected
if (selectedOption > -1) {
//set the same selected option for the second select box
document.formName.selectName2.options[selectedOption].selected = true;
}

}
</script>
</head>
<body>
<form name="formName"><div align="center">
<p>
<select name="selectName1" size="1"onchange="setSelectedOption();">
<option value="" selected="selected">-----------</option>
<option value="1">First Choice</option>
<option value="2">Second Choice</option>
<option value="3">Third Choice</option>
</select>
</p>
<p>
<select name="selectName2" size="1">
<option value="" selected="selected">---------</option>
<option value="1">First Choice</option>
<option value="2">Second Choice</option>
<option value="3">Third Choice</option>
</select>
</p>
</div></form>
</body>
</html>

No comments: