If we can find the selected value belongs to a certain Category in HTML Select tag using jQuery
-
20-06-2021 - |
Question
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
}
}
OTHER TIPS
Do you want like this?
$("#selectName").change(function(){
$val = $('#selectName :selected').parent().attr('label');
alert($val);
});
Creates an alert with the label-text of the parent group of selected element:
var $group = $('#selectName option:selected').parent();
alert($group.attr("label"));
$('select').change(function(e){
var group = $('select option:selected').parent('optgroup');
var groupText = group.attr('label');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow