使用jQuery构建选择/下拉optgroup问题

时间:2018-07-14 03:43:43

标签: javascript jquery

我想在JQuery的下拉列表中添加<optgroup>。选项正常运行,但我无法使选项组正常工作。

HTML:

<select name="DropDownID" id="DropDownID">
    <optgroup label="Foo">
        <option style="alignment: center" value="<%= alertGroup.colorValue %>" id="red7" selected disabled hidden><%= alertGroup.colorName %></option>
    </optgroup>
</select>

jQuery:

$("#DropDownID")
colorBuild(function (result) {
    var Color = result;

    for (var i = 0; i < Color.Data.length; i++) {
        $("#DropDownID").append($("<optgroup></optgroup>").attr('label', Color.Data[i].ColorText)); //<-- This is my issue
        $("#DropDownID").append($("<option></option>").val(Color.Data[i].RgbValue).text(Color.Data[i].ColorText).html(Color.Data[i].ColorName)); //<-- This is working fine

    }
});

我的console.log

{element: n.fn.init(1), index: 0, value: "df514f", label: "Red", optgroup: "Foo", …} //<-- this is coming from static HTML
56d6736dfe2cf81830b7ec0f:124 {element: n.fn.init(1), index: 1, value: "df514f", label: "Red", optgroup: "", …} //<-- I want to be able to add a value here with JQuery code above
56d6736dfe2cf81830b7ec0f:124 {element: n.fn.init(1), index: 2, value: "CD69C9", label: "Orchild", optgroup: "", …}

这是我获取值的方式:

function GetSelectedItem(el)
{
    var e = document.getElementById(el);

    color = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
    colorName = e.options[e.selectedIndex].text;
    colorValue = e.options[e.selectedIndex].value;
    optgroupValue = e.options[e.selectedIndex].optgroup; //<-- this is resolving as undefined
}

1 个答案:

答案 0 :(得分:0)

创建组,使用标签命名,然后将每个选项添加到组中。

$("#DropDownID")
colorBuild(function (result) {
    var Color = result;

    //create a constant for element
    const $sel = $('#DropDownID');

    //create a variable to hold our optgroup
    var group = $('<optgroup/>');

    //assign label to optgroup and append to select element
    group.attr('label', 'Foo2').appendTo($sel);


    for (var i = 0; i < Color.Data.length; i++) {

        //probably only need .html here, anyway, append to group
        $('<option />').val(Color.Data[i].RgbValue).text(Color.Data[i].ColorText).html(Color.Data[i].ColorName).appendTo(group);

    }
}

并获取所选的optgroup ...

optGroup = e.options[this.selectedIndex].parentNode.label