Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the selected value of a Drop down list in a text field (javascript)

For Example: These are the items in a 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 value of price1 in a text field below:

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

Thank you for answering

like image 515
NLimbu Avatar asked May 09 '12 16:05

NLimbu


People also ask

How do you display the selected value of dropdown in a text box?

All you need to do is set the value of the input to the value of the select, in a select. onchange event handler. Show activity on this post. This is the brute force way to look up the currently selected option, check its value and use its display text to update your input.


2 Answers

All you need to do is set the value of the input to the value of the select, in a 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

like image 81
jumpnett Avatar answered Sep 20 '22 03:09

jumpnett


This is the brute force way to look up the currently selected option, check its value and use its display text to update your input. Like Daniele suggested, if you have jquery at your disposal, this gets much, much easier. But if you can't use a JS framework for any reason, this should get you what you need.

<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>
like image 20
Rob S Avatar answered Sep 22 '22 03:09

Rob S