views:

185

answers:

2

Hi,

I have a form in a webpage where I would like to put the selected item in a drop down list into a testbox. The code I have till now is the following:

            <form action = "">
                <select name = "Cities">
                  <option value="----">--Select--</option>
                  <option value="roma">Roma</option>
                  <option value="torino">Torino</option>
                  <option value="milan">Milan</option>
                </select>
                <br/>
                <br/>
                <input type="button" value="Test">
                <input type="text" name="SelectedCity" value="" />
            </form>

I think I need to use javascript .... but any help? :-)

thanks

+3  A: 
<input type="button" onclick="var s = this.form.elements['Cities'];
    this.form.elements['SelectedCity'].value = s.options[s.selectedIndex].textContent">
jholster
thanks .. this work when one change the value of the dropdown list but i need to put the value once I push the button
mouthpiec
Ignore previous update, I misread you. Now it should work as you need.
jholster
A: 
 <script type="text/javascript">
    function OnDropDownChange(dropDown) {
        var selectedValue = dropDown.options[dropDown.selectedIndex].value;
        document.getElementById("txtSelectedCity").value = selectedValue;
    }
 </script>

        <form action = "">
            <select name = "Cities" onChange="OnDropDownChange(this);">
              <option value="----">--Select--</option>
              <option value="roma">Roma</option>
              <option value="torino">Torino</option>
              <option value="milan">Milan</option>
            </select>
            <br/>
            <br/>
            <input type="button" value="Test">
            <input type="text" id="txtSelectedCity" name="SelectedCity" value="" />
        </form>
xenosyde
You don't have to prefix inline event handlers with `javascript:`.
jholster
Also note that `getElementsByName()` returns a list instead of single node, so you need to access first element of it: `.getElementsByName('SelectedCity')[0].value = ...`
jholster
You are correct, thanks for pointing that out. Removed the prefix "javascript:" and also modified the script so that you can grab it from the exact element using such ID instead of a list of elements.
xenosyde