How to get the optgroup for a multiselect in jQuery
Posted on | March 16, 2012 | No Comments
Imagine you have created a web application for a small grocery shop, and as a free gift for signing up they are letting you have one free piece of fruit or one free punnet of berries. In a notification area you want to indicate to the user what type of gift they have chosen.
Using jQuery you can determine which optgroup a select option belongs to.
When populating a select element (the drop-down element) it is possible to group options together using an optgroup (meaning “options group”).
For example:
[html]
[/html]
And here is the result:
Notice how you cannot select the label for the optgroup?
Using jQuery, this is how to get the optgroup of the selected option:
[javascript]
$(“select”).find(“option:selected”).each(function(){
var label = $(this).parent().attr(“label”);
$(“#reportingArea span”).html(label);
});
[/javascript]
Line one finds the selected option in our element, then returns it’s parent – the optgroup. In this example we retrieve the label of the optgroup and replace the report area span with it.
Posted By:Richard Parnaby-King