问题
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