简体   繁体   中英

Copy select option ID value into hidden field with jQuery

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?

Its very simple: Here you go:

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

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'));
});

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

Altertaniteva way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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