Wednesday, August 29, 2012

Optgroups within Contact Form 7 in WordPress

The Contact Form 7 plugin for WordPress doesn't support select optgroups natively. I wanted to create something that would work even if the plugin is later updated, so I used jQuery.

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.

  1. The beginning of your optgroup should be an option with the value "optgroup-XYZ" where XYZ is the label you want for your optgroup.
  2. 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:

Paul said...

Hi Nathan,

Just want to say thanks ...

Works a treat!!! :-)

Nathan Markey said...

Great, glad to hear it!

Anonymous said...

Hi Nathan, may i know where should i put the code?

Nathan Markey said...

You can put it in a JavaScript script that is included on the page load on the page where the form is displayed.

Pete said...

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

Dublin Dining said...
This comment has been removed by the author.
Anonymous said...

Wonderful work! Many thanks!

Rick Torres said...

Works great, thanks !