Copying from a Drop Down List

Question: I have 100 names in my javascript drop down box. Every name has a different number ie. 1, 56, 78, 34 and so on. I want when we select a name from the drop down and then I click on a button or just when we select a name from the drop down that the number associated with that name be displayed in a text field right on that page.

Answer: The below drop down box and text field do what you describe. I have only put three "names" in the drop down list with associated values but it should be sufficient to show how the drop down list to text field copy works.

The code to produce this effect follows:

 <form name="ex" method="POST"><div class="centre">
<select name="sel" size="1"
onchange="document.ex.selvalue.value = document.ex.sel.options[document.ex.sel.selectedIndex].value;">
<option value="100" selected="selected">full</option>
<option value="5">slight</option>
<option value="50">half</option>
<input type="text" name="selvalue" size="10" maxlength="10" value="100"
onblur="document.ex.selvalue.value = document.ex.sel.options[document.ex.sel.selectedIndex].value;" />

The javascript processing is very simple. First you make sure that the text field is initially assigned the value corresponding to the selected entry in the drop down list. The onchange method attached to the select copies the value associated with the selected entry in the drop down list to the text field whenever the field is changed. The onblur method attached to the text field does the same thing to ensure that the content of the text field cannot be changed independently of the drop down list.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow