如何获取所有optgroup选项值并将它们推送到数组中

How to get all optgroup options values and push them to an array?

本文关键字:数组 选项 何获取 获取 optgroup      更新时间:2023-09-26

我有一个下拉列表,其中包含2个optgroup(Fiddle)。我现在要做的是,我想获取Around The World Kitchens optgroup中的所有选项值,并将每个值推送到一个数组中。

我正在使用$('#daily_order_kitchen_id optgroup option')瞄准元素,但它对我不起作用。

这就是我期待的结果:

["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,另一个是Around The World Kitchens

如果仅在optgourp上运行选择器,则会同时考虑两个组。

如果你想从Around The World Kitchens中获得价值,你必须特别提到

像这个

optgroup[label="Around The World Kitchens"]

这将尝试查找标签为Around The World Kitchens 的optgroup

试试这个

$('#daily_order_kitchen_id optgroup[label="Around The World Kitchens"] option').each(function () {
    arr.push($(this).val())
});

JSFIDDLE

编辑:试试这个代码。

 var selectedKitchen = $("#daily_order_kitchen_id option:selected").val();
    var arr = [];
    $('#daily_order_kitchen_id option').each(function () {
        if($(this).parent().attr('label') != 'Around The World Kitchens') {
                arr.push($(this).val());    
        }       
    });
    console.log(selectedKitchen);
    console.log(arr);