简体   繁体   English

根据选择列表选项更新输入字段

[英]updating a input field based on selectlist option

I have the following HTML我有以下 HTML

<select name="title" id="title">
  <option value="Mrs" >Mrs</option>
  <option value="Mr" >Mr</option>
  <option value="Miss" >Miss</option>
  <option value="Dr" >Dr</option>
</select>

<input type="text" name="gtitle" id="gift_title" value="" />

Now by default Mrs is shown as the first option of the select list.现在默认情况下Mrs显示为 select 列表的第一个选项。 What I need to do then, is to get this value and display it in the input field.然后我需要做的是获取该值并将其显示在input字段中。 Subsequent selections by the user, ie he/she choses Mr , must also update this input field as well.用户的后续选择,即他/她选择了Mr ,也必须更新这个输入字段。

I was hoping I could this in jQuery, but I wasn't sure how to get these values.我希望我能在 jQuery 中做到这一点,但我不确定如何获得这些值。

Thanks谢谢

You could subscribe for the .change() event of the dropdownlist and update the value of the input:您可以订阅下拉列表的.change()事件并更新输入的值:

$(function() {
    // initialize the value of the input field to the selected value
    // of the dropdown list:
    $('#gift_title').val($('#title').val());

    $('#title').change(function() {
        // when the value of the dropdown list changes
        // update the input field
        $('#gift_title').val($(this).val());
    });
});

And here's a live demo .这是一个现场演示

<select name="title" id="title">
  <option value="Mrs" >Mrs</option>
  <option value="Mr" >Mr</option>
  <option value="Miss" >Miss</option>
  <option value="Dr" >Dr</option>
</select>

<input type="text" name="gtitle" id="gift_title" value="Mrs" />

I added default value to html我将默认值添加到 html

$('#title').change(function(){
    $('#gift_title').val(this.value);
});

working demo工作演示

but I fail to see any reason for this just use the select value when you submit there should be no need for input feild但是我看不到任何原因,只需在提交时使用 select 值就不需要输入字段

In addition to the awnsers provided already, I suggest the following, to populate the input field with the default value of the checkbox at load.除了已经提供的 awnsers 之外,我还建议以下内容,以在加载时使用复选框的默认值填充输入字段。 Insert something like this between line 4 and 5 of Darin's code:在 Darin 代码的第 4 行和第 5 行之间插入类似这样的内容:

$('#gift_title').val($('#title').val());

or consider making the change callback function explicit so it could be reused.或考虑使更改回调 function 显式,以便可以重用。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM