Display the selected value of a Drop down list in

2019-02-18 07:38发布

问题:

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

回答1:

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



回答2:

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>


回答3:

$.on('change', '#cmbitems', function() {
    $('#txtprice').val($('#cmbitems option:selected').val());
});


回答4:

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();">