JavaScript to set which item in a drop-down box is selected


For setting values in a drop-down box, you can create your select box then loop through each value to find which item in the list has the value you want to pre-select.

In this example, "Alabama" is selected. In the code for this example, below, line 9 could easily be dynamically determined from a database pull, request.form, etc.

<form id="form1" name="form1" action="" method="post">

<select name="state">

<option value="none">Please select a state</option>

<option value="alabama">Alabama</option>

<option value="arkansas">Arkansas</option>

</select>

<script>

var i=0;

var selectedState = 'alabama';

while ((document.forms("form1").state.options[i].value != selectedState) && (i < document.forms("form1").state.options.length))

{i++;}

if (i < document.forms("form1").state.options.length)

{document.forms("form1").state.selectedIndex = i;}

</script>

</form>