Thank you ParkMart for starting this idea (http://wordpress.org/support/topic/how-to-add-optgroup-in-a-drop-down-menu). He ran into a bug with jQuery auto-closing the tags with his method. But this method works.
Simply create two additional options to create an optgroup.
- The beginning of your optgroup should be an option with the value "optgroup-XYZ" where XYZ is the label you want for your optgroup.
- The end of your optgroup should be an option with the value "endoptgroup".
Example:
optgroup-Title 1
item 1
item 2
item 3
endoptgroup
optgroup-Title 2
item 4
item 5
endoptgroup
Code:
// contact us form - change out optgroup labels
$(function() {
// search for optgroup- items
var foundin = $('option:contains("optgroup-")');
$.each(foundin, function(value) {
var updated = $(this).val().replace("optgroup-","");
// find all following elements until endoptgroup
$(this).nextUntil('option:contains("endoptgroup")')
.wrapAll('<optgroup label="'+ updated +'"></optgroup');
});
// remove placeholder options
$('option:contains("optgroup-")').remove();
$('option:contains("endoptgroup")').remove();
});
8 comments:
Hi Nathan,
Just want to say thanks ...
Works a treat!!! :-)
Great, glad to hear it!
Hi Nathan, may i know where should i put the code?
You can put it in a JavaScript script that is included on the page load on the page where the form is displayed.
I just installed this along with Eric Hynds jquery multi select widget http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
At first the jquery widget was displaying the optgroup titles and end option with check boxes, I was about to start modifying the code to disable the check boxes in the opening and closing option groups
But the problem was I was firing off the widget jquery first. And the solution was to simply have your code fire before the widget jquery to take care of the opt groups then the select widget fires styling the optgroups nicely.
Nice piece of code thanks
Wonderful work! Many thanks!
Works great, thanks !
Post a Comment