This tutorial will show you how to programmatically add an ID attribute to the Contact Form 7 checkbox and radio button elements using jQuery.
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 and 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 if 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 code 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, we can use jQuery to programmatically add an ID to all radio button and checkbox elements in the CF7 form. The following code will combine the value attribute and name attribute to create the ID attribute and then insert 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, and now the ID attribute is inserted into the input tag appropriately:
The method above used in this tutorial can be directly added to the contact form tab or you could use the plugin Scripts n Styles and add the code as a Hoops shortcode.