[英]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: 我看过一些教程,您可以在其中将select选项的值复制到这样的隐藏字段中:
$("#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... 但是我真正需要做的是复制ID ,所以如果我有这个...
<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()
如果要获取ID而不是值,请添加
.attr('id')
而不是.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. 还要注意,您正在丢失触发事件的
select
与正在查询以获取所选值的select
之间的关系。 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; 还要注意,在第一个示例中,您不必向下钻取选定的
option
并获取其值。 jQuery is clever enough that, if you simply ask for .val()
on the select
itself, it does this for you. jQuery非常聪明,如果您只是在
select
本身上要求.val()
,它就会为您做到这一点。
$("#my_stuff").change(function(){
$("#my_hidden_field").val($(this).val());
});
Altertaniteva way: Altertaniteva方式:
$("#my_stuff").change(function(){
$("#my_hidden_field").val($("select option:selected").prop('id'));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.