如何获取所有optgroup选项值并将其推入数组? [英] How to get all optgroup options values and push them to an array?
问题描述
我有一个下拉列表,其中包含2个optgroup(小提琴).我现在想做的是,我想获取 Around The Kitchens
optgroup内的所有选项值,并将每个值推入数组.
I have a dropdown that contains 2 optgroup inside it (Fiddle). What I'm trying to do now is, I want to grab all options values inside the Around The World Kitchens
optgroup and push each of the value into an array.
我正在使用 $('#daily_order_kitchen_id optgroup选项')
来定位元素,但是它对我不起作用.
I'm targeting the element using $('#daily_order_kitchen_id optgroup option')
but it's not working for me.
这是我期望的结果:
["11", "12", "13", "14", "15"]
HTML:
<select id="daily_order_kitchen_id" class="form-control">
<optgroup label="Default Kitchen">
<option selected="selected" value="8">Ondricka LLC</option>
</optgroup>
<optgroup label="Around The World Kitchens">
<option value="11">Erdman and Sons</option>
<option value="12">Franecki, Ryan and Homenick</option>
<option value="13">Jacobi-Sawayn</option>
<option value="14">Toy, Hane and Zboncak</option>
<option value="15">Bauch, Dach and Kihn</option>
</optgroup>
</select>
JS:
var selectedKitchen = $("#daily_order_kitchen_id option:selected").val();
var arr = [];
$('#daily_order_kitchen_id optgroup option').each(function () {
arr.push($(this).val())
});
console.log(selectedKitchen);
console.log(arr);
我该怎么办?
推荐答案
好吧, select
有两个 optgourp
,一个是 Default Kitchen
,另一个是是世界各地的厨房
.
Well, select
has two optgourp
one is Default Kitchen
and another is Around The World Kitchens
.
如果仅在 optgourp
上运行选择器,则会同时考虑这两个组.
If you run selector only on optgourp
it'll take both group in consideration.
如果您想从环游世界厨房
中获得价值,请具体提及
If you wanna get value from Around The World Kitchens
, you have mention it specificly
赞
optgroup[label="Around The World Kitchens"]
这将尝试查找标签为 The World Kitchens
尝试这样
$('#daily_order_kitchen_id optgroup[label="Around The World Kitchens"] option').each(function () {
arr.push($(this).val())
});
JSFIDDLE
这篇关于如何获取所有optgroup选项值并将其推入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!