Javascript 在下拉框中选择项目时更改文本框值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10301507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:44:57  来源:igfitidea点击:

Change Textbox value when an item is selected in drop down box

javascripthtmlselect

提问by Sana Joseph

I'm trying to change the value of a text box with the the item I select from a drop down box. But it's not working.

我正在尝试使用我从下拉框中选择的项目更改文本框的值。但它不起作用。

I tried this HTML:

我试过这个 HTML:

<select name="ncontacts" id="contacts" onchange="ChooseContact(this);"> 
</select>

and this JS:

和这个JS:

function ChooseContact(data)
{
   alert(data);
   document.getElementById("friendName").value = data;
}

But the text box val is not updated.

但是文本框 val 没有更新。

回答by James Allardice

This is because this(the argument to ChooseContact) refers to the selectelement itself, and not its value. You need to set the valueof the friendNameelement to the valueof the selectelement:

这是因为this(对 的参数ChooseContact)指的是select元素本身,而不是它的值。您需要valuefriendName元素的value设置为select元素的 :

document.getElementById("friendName").value = data.value; //data is the element

Here's a working example.

这是一个工作示例

回答by Shiv Singh

I suggest you very simple method

我建议你很简单的方法

$('#quantity').change(function(){
  var qty = $('#quantity').val();
  $("#totalprice").val(qty);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pricesection">
        <input type="hidden" id="productPrice" value="340"/>
    Quantity: 
    <select id="quantity">
        <option value="1" selected>1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
    </select>
Total: $
<input type="text" id="totalprice" value="1"/>

    
</div>