This tutorial will show you how to programmatically add an ID attribute to the Contact Form 7 checkbox and radio button elements using jQuery.
Add an ID Attribute to Contact Form 7 Checkbox Elements
The current version of Contact Form 7 does not insert the ID or class attribute into the input tag for the radio button and checkbox elements. Instead, CF7 adds it into a span tag that wraps around the input field. This poses a problem when creating a form that conditionally displays fields. Consequently, there is no way to reference the ID or class of the checkbox or radio button input type.
The examples used in this tutorial are taken from a live client’s website. The client’s form uses a checkbox to conditionally display the co-applicant part of the form when checked. This tutorial only discusses how to add the ID attribute to the input field.
Step 1. Create the Checkbox in Contact Form 7
The first step is to create the checkbox in Contact Form 7. Visit the CF7 Checkboxes, Radio Buttons, and Menus page if you are unfamiliar with the form-tag syntax. The following is used as an example:
[checkbox co-applicant-toggle id:form-occupancy-co-application-toggle exclusive use_label_element "Co-Applicant?"]
Take note that the ID attribute is not included in the input tag when viewing the HTML:
Step 2. Insert an ID Attribute Using jQuery
In order to include an ID attribute in the input tag, use jQuery to programmatically add an ID to all radio buttons and checkbox elements in the CF7 form. The following code snippet will combine the value attribute and name attribute to create the ID attribute. It then inserts it into the respective input tag.
Hat tip to the original author, but the code was missing a vital feature that would change the spaces to a dash, remove question marks, and convert the letters to lowercase:
name = name.replace(/\s+/g, '-').replace(/\?/g, '').toLowerCase();
The new code snippet has been added to line 17. As a result, the input tag has the ID attribute inserted appropriately:
Final Thoughts: Add an ID Attribute to Contact Form 7 Checkbox Elements
The method above used in this tutorial can be directly added to the contact form tab. You could also use the plugin Scripts n Styles and add the code as a Hoops shortcode.
Need help? Our WordPress Development Service is a complete solution for small, medium, and enterprise-level businesses. Call us at 602-633-4758 for a free consultation.
Thank you for this! I made one small adjustment to remove apostrophe as well! .replace(/\?/g, ”)