Search code examples
jqueryhtmlhtml-selectoptgroup

If we can find the selected value belongs to a certain Category in HTML Select tag using jQuery


I am really scratching my head to find if there is any way to find the selected group of the selected option in the HTML Select Tag.

I thought of getting parent of the selected value but could not get the right solution. but we cannot rule out this option as well.

<select id="selectName">
    <option value="0">-- Select --</option>
    <optgroup label="Section -- 1">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </optgroup>
    <optgroup label="Section -- 2">
        <option value="100">Hundred</option>
    </optgroup>
</select>

I rally do not want to write my code like this...

$val = $('#selectName').val()

if($val >=1 && $val <= 4){/* ... */}
else if(/*-- another range --*/){/* ... */}

I wonder if there is a way we can find the group name.

Thanks.


Solution

  • The following should work:

    var optgroup = $("#selectName :selected").parent("optgroup");
    if (optgroup.length) {
        var label = optgroup.attr("label");
        if (label == " ... ") {
            // do something
        }
    }
    

    DEMO: http://jsfiddle.net/3Sqjh/