jQuery 如何使用jquery获取下拉值并显示在文本框中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16600701/
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-26 17:27:12  来源:igfitidea点击:

How to get dropdown value and show in textbox using jquery?

javascriptjquerytextboxoptioncustom-data-attribute

提问by Oscar

What I want to do is get data from drop down and pass the data to textbox

我想要做的是从下拉列表中获取数据并将数据传递到文本框

here is my dropdown and textbox code

这是我的下拉菜单和文本框代码

    <select name="criteria_title" id="chosen_a" data-placeholder="Select Category" class="chzn_z span3 dropDownId chzn-done" style="display: none;">
        <option value=""></option>
        <option value="1" data-id="10">a</option>
        <option value="2" data-id="20">b</option>
        <option value="3" data-id="30">c</option>
        <option value="4" data-id="40">d</option>
        <option value="5" data-id="50">e</option>
   </select>



<div class=" control-group formSep template">
<label for="input01" class="control-label">Category Rate*:</label>
<div class="controls">
<input id="title" name="criteria_rate" size="30" type="text" class="criteria_rate span2" value=""  readonly="readonly" />
</div>
</div>

here is how to get data-id from dropdown

这是如何从下拉列表中获取数据 ID

var criteria_id =  $(this).attr('data-id');

here is how to pass data to textbox

这是将数据传递给文本框的方法

$('.criteria_rate').val(criteria_id);

here is my dropdown screenshotenter image description here

这是我的下拉屏幕截图在此处输入图片说明

Any idea how to solve my problem?

知道如何解决我的问题吗?

采纳答案by PSL

Try this:-

尝试这个:-

$('#chosen_a').change(function(){
     //get the selected option's data-id value using jquery `.data()`
      var criteria_rate =  $(':selected',this).data('id'); 
     //populate the rate.
    $('.criteria_rate').val(criteria_rate);
});

Fiddle

小提琴

Refer .data()

参考.data()

回答by VVV

Here is what you need (I think)

这是你需要的(我认为)

FIDDLE

小提琴

$('#chosen_a').change(function() {
    $('#title').val($('#chosen_a option:selected').data('id'));
})

回答by lamass

This is the most simple way

这是最简单的方法

$(document).ready(function () {
    $("#chosen_a").change(function () {
      $('#title').val($("#chosen_a").val());


    });

});

回答by Xotic750

Here is a possible solution, uses jquery but get the data through the event data instead of using jquery.data(notice that it is a few characters shorter doing it this way :P )

这是一个可能的解决方案,使用 jquery 但通过事件数据而不是使用jquery.data获取数据(请注意,这样做会缩短几个字符:P)

$("#chosen_a").on("change", function (evt) {
    $("#title").val(evt.target.selectedOptions[0].dataset.id);
});

Demonstrated on jsfiddle

jsfiddle演示

(gave an alternative as I misread the question initially, so now I'm a little late with my correction)

(因为我最初误读了这个问题,所以给出了一个替代方案,所以现在我的更正有点晚了)