6

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

Daniele B
  • 3,117
  • 2
  • 23
  • 46
NLimbu
  • 151
  • 1
  • 4
  • 10

4 Answers4

7

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

jumpnett
  • 6,967
  • 1
  • 19
  • 24
1

If you are using jquery just go with

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

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

First, inlcude jquery in your html file.

In the <header> you include it:

<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();">
Daniele B
  • 3,117
  • 2
  • 23
  • 46
  • sorry i forgot to mention in javascript – NLimbu May 09 '12 at 16:41
  • This will only give you the value of the selected element(s).. not populate them in the input. Check my answer below for more details. – Nick George May 09 '12 at 16:41
  • jquery is a javascript library created to make your life easier! Have a look at it and then you'll discover a whole new - simplier - way of coding. – Daniele B May 09 '12 at 16:42
1

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>
Rob S
  • 211
  • 1
  • 8
1
$.on('change', '#cmbitems', function() {
    $('#txtprice').val($('#cmbitems option:selected').val());
});
Nick George
  • 327
  • 3
  • 9