Copy select option ID value into hidden field with jQuery

蹲街弑〆低调 提交于 2021-01-29 05:01:10

问题


I've seen a few tutorials where you can copy the value of a select option into a hidden field like this:

$("#my_stuff").change(function(){
    $("#my_hidden_field").val($("select option:selected").val());
});

So if I had this...

<select name="my_stuff" id="my_stuff">
    <option value="Red">Red things</option>
    <option value="Green">Green things</option>
    <option value="Blue">Blue things</option>
</select>

...and selected 'Red things', then 'Red things' would be copied into the hidden field value.

But what I really need to do is copy the ID instead, so if I had this...

<select name="my_stuff" id="my_stuff">
    <option value="Red" id="all the red stuff">Red things</option>
    <option value="Green" id="all the green stuff">Green things</option>
    <option value="Blue" id="all the blue stuff">Blue things</option>
</select>

...and I selected 'Red things', then 'all the red stuff' would be copied into the hidden field.

Is this even possible?


回答1:


Its very simple: Here you go:

$("#my_stuff").change(function(){
    $("#my_hidden_field").val($("select option:selected").attr('id'));
});



回答2:


If you want to get id instead of value then add .attr('id') instead of .val()

$("#my_stuff").change(function(){
    $("#my_hidden_field").val($("select option:selected").attr('id'));
});



回答3:


Of course.

$("#my_stuff").change(function(){
    $("#my_hidden_field").val($(this).children(":selected").attr('id'));
});

Note also that you're losing the relationship between the select that fired the event, and the select you're interrogating to get the chosen value. Change:

$("select option:selected") //any select, not necessarily the event trigger

to

$(this).children(":selected") //specifically, the select that triggered the event

Note also that, in the first example, you don't have to drill down to the selected option and get its value; jQuery is clever enough that, if you simply ask for .val() on the select itself, it does this for you.

$("#my_stuff").change(function(){
    $("#my_hidden_field").val($(this).val());
});



回答4:


Altertaniteva way:

$("#my_stuff").change(function(){
   $("#my_hidden_field").val($("select option:selected").prop('id'));
});


来源:https://stackoverflow.com/questions/50153197/copy-select-option-id-value-into-hidden-field-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!