Display selected dropdown value in text box (javascript)

For example: These are items in the drop-down list.

<select name="cmbitems" id="cmbitems">
    <option value="price1">blue</option>
    <option value="price2">green</option>
    <option value="price3">red</option>
</select>

When the user selects blue, I want to display the price1 value in the text box below:

<input type="text" name="txtprice" id="txtprice" onClick="checkPrice()">

Thanks for answering

+3
source share
4 answers

All you have to do is set the input value to select in the select.onchange event handler.

var select = document.getElementById('cmbitems');
var input = document.getElementById('txtprice');
select.onchange = function() {
    input.value = select.value;
}

Here is a link to a jsFiddle demo

+4
source

If you are using jquery just select

$('select.foo option:selected').val();    // get the value from a dropdown select

UPDATE (I forgot to include the population <input>)

First, inlcude jquery in your html file.

In <header>you turn it on:

<header>
<script type="text/javascript" src="YOUR_PATH_TO_LIBRARY/jquery-1.7.1-min.js"></script>
</header>

Then

<input type="text" name="txtprice" id="txtprice" onClick="javascript:$('select.foo option:selected').val();">
0

, . , jquery , . JS- - , , .

<select name="cmbitems" id="cmbitems" onchange="updateTextField()">
 ...
</select>
<input type="text" ..... />

<script type="text/javascript">
function updateTextField()
{
    var select = document.getElementById("cmbitems");
    var option = select.options[select.selectedIndex];
    if (option.id == "price1")
    {
        document.getElementById("txtprice").value = option.text;
    }
}
</script>
0
$.on('change', '#cmbitems', function() {
    $('#txtprice').val($('#cmbitems option:selected').val());
});
0

All Articles