Below are some commonly requested customizations that require javascript in your WordPress forms. The best place to add these code samples is either in your Theme's footer section or the "After Fields" section of your Form Settings → "Customize HTML" tab.
Forms
Conditionally show a form
If you would like to display a form based on a single checkbox selection, you may insert the following code on the same page as your form shortcode. This will add a checkbox to your page which, if selected, will display your form.
<script type="text/javascript">
function showMe (it, box) {
var vis = (box.checked) ? "block" : "none";
document.getElementById(it).style.display = vis;
}
</script>
Show Form: <input type="checkbox" name="multi_note" value="1" onclick="showMe('div1', this)">
<div id="div1" style="display:none">
[formidable id=18]
</div>
Replace '18' with the ID of your form.
You may want to display your form if a user selects "Yes" or hide your form and display a message if they select "No". Insert this code on a page to achieve this functionality.
<form>
Show form?
<input type="radio" id="showform" value="yes" name="showform" onchange="showhideForm(this.value);"/>Yes
<input type="radio" id="showform" value="no" name="showform" onchange="showhideForm(this.value);"/>No
</form>
<script type="text/javascript">
function showhideForm(showform) {
if (showform == "yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
if (showform == "no") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
}
}
</script>
<div id="div1" style="display:none">
[formidable id=18]
</div>
<div id="div2" style="display:none">
You are not qualified to see this form.
</div>
Replace '18' with the ID of your form.
Reset Form
This code will clear all fields and selections
<a href="#" onclick="document.getElementById('form_[form_key]').reset();">Reset Form</a>
Paste this code in at the end of your "Submit Button" section on your "Customize HTML" Page. No modification is necessary as it will automatically retrieve the proper form_key, however if you use this code elsewhere on a page, you may need to manually enter the field key in place of [form_key].
Conditionally disable submit button
Note: This is now a built-in feature of Formidable Forms premium.
You can disable the submit button on your form preventing it from being submitted unless certain options are selected. This example will disable the submit button if "No" is selected for any of the three fields (25, 26, and 27).
<script type="text/javascript"> jQuery(document).ready(function($){ var $submitInput = $("#frm_form_23_container input[type=submit]"); var $submitButton = $("#frm_form_23_container button[type=submit]"); var fieldOne = 25; var fieldTwo = 26; var fieldThree = 27; //disable submit button by default $submitInput.attr('disabled','disabled'); $submitButton.attr('disabled','disabled'); $("input[name^='item_meta[" + fieldOne + "]'], input[name^='item_meta[" + fieldTwo + "]'], input[name^='item_meta[" + fieldThree + "]']").change(function(){ var submit = true; if($("input[name^='item_meta[" + fieldOne + "]']:checked").val() == 'No' || $("input[name^='item_meta[" + fieldTwo + "]']:checked").val() == 'No' || $("input[name^='item_meta[" + fieldThree + "]']:checked").val() == 'No') { submit = false; } if(submit){ $submitInput.removeAttr('disabled'); $submitButton.removeAttr('disabled'); } else { $submitInput.attr('disabled','disabled'); $submitButton.attr('disabled','disabled'); } }); }); </script>
To make this example work for your form, replace "23"(2 locations) with the ID of your form, replace 25, 26, and 27 with the ID's of your fields, and replace "No" with value that should disable the submit button.
Conditionally hide submit button
Note: This is now a built-in feature of Formidable Pro.
Hide the submit button on your form until certain fields are filled in. This example will hide the submit button until "Yes" is selected in a checkbox field.
<script> jQuery(document).ready(function($){ var formID = 10; var fieldID = 25; var showVal = 'Yes'; var $submitButton = $("#frm_form_" + formID + "_container .frm_final_submit"); //Hide submit button by default if Yes is not already checked if (($("input[name^='item_meta[" + fieldID + "]']:checked").val() != showVal) && ($("input[type=hidden][name^='item_meta[" + fieldID + "]']").val() != showVal)) { $submitButton.css('visibility','hidden'); } $("input[name^='item_meta[" + fieldID + "]']").change(function(){ if ($("input[name^='item_meta[" + fieldID + "]']:checked").val() == showVal){ $submitButton.css('visibility','visible'); }else{ $submitButton.css('visibility','hidden'); } }); }); </script>
Replace 10 with the ID of your form, replace 25 with the ID of your field, and replace Yes with value that should show the submit button. Please note that this code example is set up to work with "Yes" as the only (or first) option in the checkbox field.
If you want to hide the submit button until 'Yes' or 'No' is selected in a checkbox field, use the following example:
<script> jQuery(document).ready(function($){ var formID = 10; var fieldID = 25; var showVal = 'Yes'; var showVal2 = 'No'; var $submitButton = $("#frm_form_" + formID + "_container .frm_final_submit"); //Hide submit button by default if Yes is not already checked if (($("input[name^='item_meta[" + fieldID + "]']:checked").val() != showVal || $("input[name^='item_meta[" + fieldID + "]']:checked").val() != showVal2) && ($("input[type=hidden][name^='item_meta[" + fieldID + "]']").val() != showVal)) { $submitButton.css('visibility','hidden'); } $("input[name^='item_meta[" + fieldID + "]']").change(function(){ if ($("input[name^='item_meta[" + fieldID + "]']:checked").val() == showVal || $("input[name^='item_meta[" + fieldID + "]']:checked").val() == showVal2){ $submitButton.css('visibility','visible'); }else{ $submitButton.css('visibility','hidden'); } }); }); </script>
Conditionally hide Next buttons in a multi-page form
This example will hide the Next buttons in a multi-page form unless "Yes" is selected in a Radio button field.
<script> jQuery(document).ready(function($){ var fieldID = 18; var showVal = 'Yes'; var $nextButton = $(".frm_button_submit"); //Hide next button by default if Yes is not already checked if (($("input[name^='item_meta[" + fieldID + "]']:checked").val() != showVal) && ($("input[type=hidden][name^='item_meta[" + fieldID + "]']").val() != showVal)) { $nextButton.css('visibility','hidden'); } $("input[name^='item_meta[" + fieldID + "]']").change(function(){ if ($("input[name^='item_meta[" + fieldID + "]']:checked").val() == showVal){ $nextButton.css('visibility','visible'); } else { $nextButton.css('visibility','hidden'); } }); }); </script>
Fields
Referencing Field Types
Each field type must be referenced differently in JavaScript. Listed below are the basic ways to references fields in JavaScript.
- Text Input (date, number, etc...):
#field_key
- Dropdown:
select[name='item_meta[994]']
- Multiple Select Dropdown:
select[name='item_meta[994][]']
- Radio Button:
input[name="item_meta[988]"]
- Checkbox/Toggle:
input[name='item_meta[453][]']
Replace 'key' with a field key and replace any numbers in red with a field ID. See each of these field types in an example here.
Conditionally hide/show a field
This option is built-in to Formidable, but there may be times where you want more options than Formidable offers. Here's a basic example that shows how to create your own conditional logic to show/hide a field.
<script type="text/javascript"> jQuery(document).ready(function($){ // Hide field by default $("#frm_field_363_container").css('display','none'); $('select[name="item_meta[125]"]').change(function(){ var show; var val1 = $("select[name='item_meta[125]']").val(); if (val1 == 'A') {show = true;} else if (val1 == 'B') {show = false;} if(show){ $("#frm_field_363_container").css('display','block'); }else{ $("#frm_field_363_container").css('display','none'); } }); }); </script>
Replace 363 with the ID of the field to hide/show. Replace 125 with the ID of the field that triggers the hide/show. In this example, 125 is a dropdown field. If you want to change it to another field type, take a look at how to reference different field types.
Conditionally hide/show a field based on the selected country in the address field
Here's a basic example that shows a field only if the user selects Uganda as their country in the address field.
<script type="text/javascript"> jQuery(document).ready(function($){ // Hide field by default var hideme = $("#frm_field_123_container"); hideme.css('display','none'); $('select[name="item_meta[456][country]"]').change(function(){ var val1 = $(this).val(); if (val1 == 'Uganda'){ hideme.show(); } else{ hideme.hide(); } }); }); </script>
Replace 123 with the ID of the field to hide/show. Replace 456 with the ID of the address field. Change Uganda to the country to check for.
Clear a field selection
You can clear a field selection when another field is changed. This can be helpful when conditionally hiding/showing fields to prevent a hidden field from retaining a selected value.
This example will change two dropdown(select) fields to a blank option when the radio button (input) is changed.
<script type="text/javascript"> jQuery(document).ready(function($){ $('input[name="item_meta[30]"]').change(function(){ $('select[name="item_meta[31]"], select[name="item_meta[32]"]').val(''); }) }) </script>
Change 30 to the ID of the radio field, and 31 and 32 to the IDs of the dropdowns. Also, change "input" and "select" to match the types of fields contained in your form. input is used for checkbox and radio button fields, select is used for dropdown fields.
For more examples on clearing fields, see the community tips and tricks.
Trigger conditional logic when typing
By default, the conditional logic and calculations are triggered when the user clicks outside of the field. You can trigger this checking to happen each time a key is pressed with this script. In some cases, 'keyup' may be a better alternative to 'keypress'.
<script> jQuery(document).on('keypress', '.frm-show-form input[name^="item_meta"], .frm-show-form select[name^="item_meta"], .frm-show-form textarea[name^="item_meta"]', function(){ jQuery(this).change(); }); </script>
Display Field Values in HTML Field
Typically, you can put field values in an HTML field with the field ID shortcodes. There are limitations to these shortcodes within the form, however. The shortcode for field 25, for example, will only work if it is inserted on a different page than field 25. Also, the field ID shortcodes will always get the saved value, but there may be times when the option label is needed. Here's a basic example for populating an HTML field with field values:
<script type="text/javascript"> jQuery(document).ready(function($){ //Use this section if your users will be allowed to edit the form var field_1 = $("#field_6j2syb").val(); var field_2 = $("input[name='item_meta[456]']:checked").val(); document.getElementById("field_1_div").innerHTML = field_1; document.getElementById("field_2_div").innerHTML = field_2; //This will change the displayed values on the fly $('#field_6j2syb, input[name="item_meta[456]"]').change(function(){ var field_1 = $("#field_6j2syb").val(); var field_2 = $("input[name='item_meta[456]']:checked").val(); document.getElementById("field_1_div").innerHTML = field_1; document.getElementById("field_2_div").innerHTML = field_2; }); }); </script>
This example uses a text field (Key 6j2syb) and a radio button field (ID 456). In order for this example to work, you must add two divs to your HTML field, like this:
Field 1: <div id="field_1_div"></div> Field 2: <div id="field_2_div"></div>
The div IDs can be modified. Just make sure you modify the div IDs in the JavaScript example as well.
Check all options
Use the code below to check all options in a checkbox field. You'll need to add a separate "Check All" checkbox or radio button field that will be used to check all of the options. Replace 2oz2d with the field key of the "Check all" field. Replace 213 with the field ID of the checkbox field that should get all options checked.
<script type="text/javascript"> jQuery(document).ready(function(){ var checkAll = document.getElementById('field_2oz2d-0'); checkAll.onchange = function(){ var set = false; if (this.checked) { set = true; } var checkboxes = document.getElementsByName('item_meta[213][]'); for (var i = 0, n = checkboxes.length; i < n; i++){ checkboxes[i].checked = set; } }; }); </script>
Check all options in Lookup field
Use the code below to check all options in a Lookup > Checkbox field, by default. This will only apply to Lookup > Checkbox fields that are watching another Lookup field. Replace 295 (in two places) with the ID of the Lookup > Checkbox field.
<script type="text/javascript"> jQuery(document).ready(function(){ var checkBoxDiv = jQuery( document.getElementById( 'frm_field_295_container' ) ); checkBoxDiv.on( 'frmLookupOptionsLoaded', function() { var checkboxes = document.getElementsByName('item_meta[295][]'); for ( var i = 0, n = checkboxes.length; i < n; i++){ checkboxes[i].checked = true; } }); }); </script>
Count number of checked boxes
Use this code to count the number of checked boxes in a Checkbox field, and insert that number in a text field or hidden field.
<script type="text/javascript"> jQuery(document).ready(function($){ $('input[name="item_meta[643][]"]').change(function(){ var val1 = $("input[name='item_meta[643][]']:checked").length; $("#field_wzfsfs").val(val1); $("#field_wzfsfs").change(); }); }); </script>
Replace 643 with the ID of your checkbox field and replace wzfsfs with the KEY of your field that will hold the total count.
Limit the number of checked boxes
Note: This is now a built-in feature of Formidable Forms premium.
Use this code to limit the number of checked boxes in a Checkbox field. Change 3 to the limit you want to set and replace 364 (in two places) with the ID of your checkbox field. This will prevent the user from selecting more than 3 options.
<script type="text/javascript"> jQuery(document).ready(function($){ var limit = 3;// Change 3 to your limit $('input[name="item_meta[364][]"]').change(function(){ var checkbox_num = $("input[name='item_meta[364][]']:checked").length; if ( checkbox_num > limit ) { this.checked = false; } }); }); </script>
If you would like to limit the number of options checked in a checkbox including the "Other" option, you can use this code instead.
<script type="text/javascript"> jQuery(document).ready(function($){ var limit = 3;// Change 3 to your limit $('#frm_field_364_container input[type="checkbox"]').change(function(){ var checkbox_num = $('#frm_field_364_container input[type="checkbox"]:checked').length; if ( checkbox_num > limit ) { this.checked = false; } }); }); </script>
Get option label from dropdown
This code can be used to get the option label from a dropdown field and store it in a hidden field. This is helpful if you need to get the text value from a Dynamic field or if you are using a Dropdown field with Separate Values enabled.
<script type="text/javascript"> jQuery(document).ready(function($){ $(document).on('change', 'select[name="item_meta[125]"]', function(){ var val1 = $("select[name='item_meta[125]']").children("option").filter(":selected").text().trim(); $("#field_FIELDKEY").val(val1); $("#field_FIELDKEY").change(); }); }); </script>
Get option value from multiple select dropdown
This code can be used to get the option value from a multiple select dropdown field.
<script type="text/javascript">
jQuery(document).ready(function($){
var values,
dropdownField = "select[name='item_meta[125][]']";
$(document).on('change', dropdownField, function(){
var values = $(dropdownField).val();
//do something
});
});
</script>
Get option label from Radio Button
This code can be used to get the option label from a Radio Button field and store it in a Hidden or other text field. This is helpful if you need to get the text value from a Dynamic field or if you are using a Radio Button field with separate values enabled.
<script type="text/javascript"> jQuery( document ).ready( function ( $ ) { $( document ).on( 'change', 'input[name="item_meta[5133]"]', function () { var val1 = $( "input[name='item_meta[5133]']" ).filter( ":checked" ).closest( 'label' ).text().trim(); $( "#field_1hfd3" ).val( val1 ); $( "#field_1hfd3" ).change(); } ); } ); </script>
Replace 5133 with the ID of the Radio Button field and lhfd3 with the field key of your Hidden field.
Get option labels from Checkboxes
This code can be used to get the option labels from the selected options in a Checkboxes field and store them in a Hidden or other text field. This is helpful if you need to get the text values from a Dynamic field or if you are using a Checkboxes field with separate values enabled.
<script type="text/javascript"> jQuery(document).ready(function($){ $('input[name="item_meta[4673][]"]').change(function(){ let choices = $("input[name='item_meta[4673][]']:checked").map(function () { return jQuery(this).parent().text().trim(); }).get().join(", "); $("#field_p7q6d").val(choices) }); }); </script>
Replace 4673 with the ID of the Checkboxes field (in two places) and p7q6d with the field key of your Hidden or other text field.
Hide option in select
Use jQuery to hide hide select option. This will allow you to remove an option from a dropdown field without deleting it. The following jQuery snippet can go in the 'After fields' box at the bottom of the customizable HTML. Change #field_25 to reference your field and change "5" to the saved value of the option to hide.
<script type="text/javascript"> jQuery('#field_25').children('option[value="5"]').css('display','none'); </script>
Instead of .css, you can also use
.hide();
or
.attr('disabled','disabled');
Get text from Dynamic List field
Add this script to your form's Settings > Customize HTML in the Before Fields. This will get the value from a "list" Data from Entries field and will put the value in a regular text field. Replace 'dfe' in the example below with the key of the Data from Entries dropdown field that the "list" field is dependent on. Replace 'hidden' with the key of a regular text field or hidden field in your form. Replace 'just_show_it' with the field key of your "list" field.
<script type="text/javascript"> jQuery(document).ready(function($){ var oldValue = ''; var dynamic_field = document.getElementById("field_dfe"); var hidden_field = document.getElementById("field_hidden"); var aTimer; var counter; $(dynamic_field).change(function(){ oldValue = $("#field_just_show_it").val() ; if (!(aTimer == undefined) ) clearInterval(aTimer) ; counter = 0 ; aTimer = setInterval(function(){ var newValue = $("#field_just_show_it").val() ; counter ++ ; if ( (newValue != oldValue) ){ if (newValue != oldValue && newValue != undefined) { hidden_field.value = newValue; oldValue = newValue; $(hidden_field).change(); } clearInterval(aTimer) ; } } , 100) ; }) ; }) ; </script>
Select matching Dynamic field
The code allows a user to select an entry using a Lookup field and have the same entry automatically selected in a Dynamic field. If there are multiple options in the Dynamic field with the same text, the first one will be selected.
<script type="text/javascript"> jQuery(document).ready(function ($) { $(document).on('change', 'select[name="item_meta[5914]"]', function () { var lookup_val = $(this).val(); $("select[name='item_meta[5915]'] option").filter(function () { return $(this).text() === lookup_val; }).first().prop('selected', true).siblings().prop('selected', false); $("select[name='item_meta[5915]']").trigger({ type:'change', originalEvent:'custom' }); }); }); </script>
Replace 5914 with the id of the Lookup field and 5915 with the id of the Dynamic field.
Calculate final date
If you would like to calculate a date from a start date and a number of days, you may use the code below. Replace add_days with the key of your field that determines the number of days. Replace date_one with the key of your first date field. Replace date_two with the key of your second date field. This code can be added to your form's Settings > Customize HTML in the Before or After fields.
<script type="text/javascript"> jQuery(document).ready(function($){ $('#field_add_days, #field_date_one').change(function(){ var addDays = $("#field_add_days").val(); var dateOneString = $("#field_date_one").val(); if ( addDays === '' || dateOneString === '' ) { return; } var finalDate = $("#field_date_one").datepicker( 'getDate' ); finalDate.setDate(finalDate.getDate() + parseInt( addDays ) ); $("#field_date_two").focusin(); $("#field_date_two").datepicker("setDate", finalDate); $("#field_date_two").change(); }); }); </script>
Format a Slider Field value as a currency
Note: This is now a built-in feature of the plugin.
The following example will format the value displayed below a Slider field as a currency, separated by commas. Note: This example requires HTML, CSS, and JavaScript.
- Add this HTML to your form's Settings → Customize HTML tab. Find the box for your slider field. Add this under [input] and replace $50 with your default slider field value.
Note: You will need to manually change the default slider amount based on where you dragged the handle.<span id="frm_range_value_display" class="frm_range_value_currency">$50</span>
- Add the following CSS in Customize HTML → Before Fields. Replace jhifa with your slider field key.
<style type="text/css"> /* add styling for the new span */ .frm_range_value_currency { text-align:center; font-size:16px; display:block; } /* make the default span hidden. Replace jhifa with your slider field key. */ #field_jhifa ~ .frm_range_value { display:none !important; } </style>
- Finally, add the following script and make the changes specified in the code. Replace jhifa with your slider field key. Change $ to your currency symbol.
<script type="text/javascript"> jQuery(document).ready(function($){ $("#field_jhifa ~ .frm_range_value").on('DOMSubtreeModified' , function(){ //change jhifa to the field key of your slider field var n = $("#field_jhifa").val(); //change jhifa to the field key of your slider field n = numberWithCommas(n); maxval = $("#field_jhifa").attr("max") //change jhifa to the field key of your slider field max = numberWithCommas(maxval); if(n == max) n += "+"; //add a + sign if slider value is equal to max value set in slider field $("#frm_range_value_display")[0].innerText = "$" + n; // add the currency symbol var event = new Event("change"); $("#frm_range_value_display")[0].dispatchEvent(event); }); //add commas const numberWithCommas = (x) => { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } }); </script>
Add commas to a number
Use this code example to add commas as thousand separators to a number. This example will add commas as the user types in a number. It also works with a calculation that uses field values.
Limitation: This code snippet is not meant to work with repeaters.
Add the frm_number_style class in CSS Layout Classes to the fields to which you want commas to be inserted automatically.
Notes:
- Commas aren't valid characters for Number fields, so this code can't be used with Number fields.
- If you want to have the number in a Number field, a potential workaround is to have the user enter the number in a Single Line Text field, with commas. Then use a numeric calculation to copy the entered number into a Number field.
If you add the frm_hidden class to the Number field, the Number field won't show in the form. - This code example reformats the number as it is changed. It isn't set up to work for default values that remain constant.
- The code example uses English formatting by default. JavaScript's toLocaleString method can be used for a variety of languages and number formats, including currencies (examples below). Please see this MDN article on the Number.toLocaleString method for more information.
<script type="text/javascript"> jQuery(document).ready(function ($) { $('.frm_number_style input').change(function () { //add the frm_number_style class to the field(s) you want to have commas var val = this.value; if (typeof val == 'undefined' || isNaN(val) || val == '') { this.value = 0; } else { this.value = parseFloat(val).toLocaleString('en'); } }); }); </script>
Show number as US dollars
The code for adding commas above can be adjusted to show numbers as currency. For example, you could show the number in US dollars like so:
<script type="text/javascript"> jQuery(document).ready(function ($) { $('.frm_currency_usd_style input').change(function () { //add the frm_currency_usd_style class to the field(s) you want to show as US dollars var val = this.value; if (typeof val == 'undefined' || isNaN(val) || val == '') { this.value = 0; } else { this.value = parseFloat(val).toLocaleString('en', { style: 'currency', currency: 'USD'}); } }); }); </script>
Add the frm_currency_usd_style class to fields that you want to show numbers as US dollars.
Show number as Japanese Yen
You can show the number as Japanese Yen like so:
<script type="text/javascript"> jQuery(document).ready(function ($) { $('.frm_currency_yen_style input').change(function () { //add the frm_currency_yen_style class to the field(s) you want to show as Japanese yen. var val = this.value; if (typeof val == 'undefined' || isNaN(val) || val == '') { this.value = 0; } else { this.value = parseFloat(val).toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }); } }); }); </script>
Add the frm_currency_yen_style class to fields that you want to show numbers as Japanese Yen.
Add commas to a copy of a number
Use this code example if you have enabled currency calculations for a Number field and want to copy that value to another field separated by commas.
- Since commas are not valid characters for number fields, use a text field for copying the number with commas.
- Add the following script and make the changes specified in the code. Replace esbct with the field KEY of your text field. Replace 395 with the field ID of your number field that has currency calculations enabled.
<script type="text/javascript"> jQuery( document ).ready( function ( $ ) { $( 'input[name="item_meta[395]"]' ).change( function () {//change 395 to the id of field with the number var val = this.value; if ( typeof val !== 'undefined' ) { $( '#field_esbct' ).val( parseFloat( val ).toLocaleString( 'en' ) );//change esbct to the key of the field with the copy of the number, with commas added as a thousands separator } }); }); </script>
Add Plus/Minus button to number field
Use this code example to add a plus/minus button to a number field. It will allow you to increase/decrease the value of the number using the icons on the Before and After input.
- Add icons to the before and after input setting of your field.
- Add the following script and make the changes specified in the code. Replace field_lahhzw with the field key of your number field and change 5983 with the field ID of your number field.
<script type="text/javascript"> jQuery(document).ready(function ($) { var val1 = $("#field_lahhzw").val(); var curr_val= val1 !==""? val1 : 0; $('#frm_field_5983_container .frm_inline_box:first-child').click(function () { curr_val--; $("#field_lahhzw").val(curr_val); $("#field_lahhzw").change(); }); $('#frm_field_5983_container .frm_inline_box:nth-last-child(1)').click(function () { curr_val ++; $("#field_lahhzw").val(curr_val); $("#field_lahhzw").change(); }); }); </script>
Add a listener for a dynamic number of rows in a repeater
Sometimes you may need to add a listener for a field within a repeater with a dynamic number of rows. The example below will watch for a change in a date field in a repeater and will insert the day of the chosen date inside a corresponding text field in the same row of the repeater:
<script type="text/javascript"> jQuery(document).on('change', '[id^=field_9nuyb]', updateDayFields ); //change 9nuyb to the field Key of the date field function updateDayFields(){ var DateFields = document.querySelectorAll( '.frm_field_5832_container input'); //change 5832 to the ID of the date field var DayFields = document.querySelectorAll( '.frm_field_5833_container input'); //change 5833 to the ID of the text field for ( var i = 0; i < DateFields.length; i++ ) { var d = DateFields[i].value; //Use the following two lines if your date format is dd/mm/yyyy var dateParts = d.split("/"); var n = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]).getDay(); //Uncomment the following line if your date format is mm/dd/yyyy and comment out the previous two lines // var n = new Date(d).getDay(); if(n == 0) //Insert the day of the week based on the date chosen DayFields[i].value = "Sunday"; else if(n == 1) DayFields[i].value = "Monday"; else if(n == 2) DayFields[i].value = "Tuesday"; else if(n == 3) DayFields[i].value = "Wednesday"; else if(n == 4) DayFields[i].value = "Thursday"; else if(n == 5) DayFields[i].value = "Friday"; else if(n == 6) DayFields[i].value = "Saturday"; } } </script>
The following line is the listener for each date field in the repeater:
jQuery(document).on('change', '[id^=field_9nuyb]', updateDayFields );
Copy a calculated value from a repeater to another repeater
Sometimes you may need to calculate a value (like a total) in one repeater, and use that in another repeater for a different calculation. In this case, you can use the example below, which will watch for a change in a calculated field (wxle9) outside of a repeater, and when that field changes, a repeater row is added, or a repeater row is removed, that field value (wxle9) will be copied and placed into another field (12622) in every row in a second repeater:
<script type="text/javascript"> jQuery(document).ready(function($){ $("#field_wxle9").change(copyValueToRepeat); jQuery(document).on('frmAfterAddRow frmAfterRemoveRow', copyValueToRepeat ); function copyValueToRepeat(){ var sourceField = document.getElementById( 'field_wxle9' ); var repeatFields = document.querySelectorAll( '.frm_field_12622_container input'); for ( var i = 0, len=repeatFields.length; i<len; i++ ) { repeatFields[i].value = sourceField.value; repeatID = repeatFields[i].id; $("#" + repeatID).change(); } } }); </script>
Add row counter
Use the code below to keep track of the number of rows in a repeater. Just add a text field to your repeater to hold the row number. Replace 186 with the ID of the text field.
<script type="text/javascript"> document.addEventListener("DOMContentLoaded", updateRepeatCountFields ); jQuery(document).on('frmAfterAddRow', updateRepeatCountFields ); jQuery(document).on('frmAfterRemoveRow', updateRepeatCountFields ); function updateRepeatCountFields(){ var countFields = document.querySelectorAll( '.frm_field_186_container input'); for ( var i = 0, len=countFields.length; i<len; i++ ) { countFields[i].value = i+1; } } </script>
Add a Word Counter
This example is designed to count the number of words in a text area field, and insert that count into an HTML field.
Replace 'r1mqrw' with the KEY of your text area field and you need to add an HTML field below the text area field to display the count. Replace 400 with the ID of your HTML field. You can add this javascript to your form's Settings > Customize HTML in the Before Fields.
<script type="text/javascript"> jQuery(document).ready(function($){ $('#field_r1mqrw').keyup(function(){ var s = this.value; s = s.replace(/(^s*)|(s*$)/gi,""); s = s.replace(/[ ]{2,}/gi," "); s = s.replace(/n /,"n"); document.getElementById("frm_field_400_container").innerHTML = (s.split(' ').length) + ' words'; }); }); </script>
Add a Character Counter
This example is designed count the number of characters in a text area field and insert that count into an HTML field.
Replace 'ga45q' with the KEY of your text area field. You need to add an HTML field below the text area field to display the count. Replace 375 with the ID of your HTML field.
<script type="text/javascript"> jQuery( document ).ready( function ( $ ) { $( '#field_ga45q' ).keyup( function () { var characters = this.value; document.getElementById( "frm_field_375_container" ).innerHTML = ( characters.length ) + ' characters'; } ); } ); </script>
Embed a selected YouTube video
This code example allows the user to select a YouTube video from a Dropdown and have that video display and be ready for playing in an HTML field.
The Dropdown options are YouTube video IDs, such as d2IPmicn2x8. You can find the YouTube video ID in the embed code or URL of a YouTube video, such as https://www.youtube.com/watch?v=d2IPmicn2x8. The Dropdown can use separate values so the user sees human readable names and the saved value is the YouTube video id.
<script type="text/javascript"> jQuery(document).ready(function($){ //This will embed a YouTube video selected in a Dropdown into an HTML field var $youtube_field = $("select[name='item_meta[5570]']");//change 5570 to ID of the field with YouTube video id selection. $youtube_field.change(function () { var youtube_id = $youtube_field.val(); document.getElementById("youtube_div").innerHTML = '<iframe width="560" height="315" src="https://www.youtube.com/embed/' + youtube_id + '" frameborder="0" allowfullscreen></iframe>';//You can change the dimensions and other attributes as you like. }); }); </script>
Replace 5570 with the ID of the Dropdown with the selection of YouTube video IDs. In order for this example to work, you need a div in your HTML field, like this:
<div id="youtube_div"></div>
The div ID can be modified. Just make sure you modify the div ID in the JavaScript example as well.
Check a checkbox based on the value of another field
<script type="text/javascript"> jQuery(document).ready(function($){ var number_field_id = '#field_tsuyo', //Replace tsuyo with the field key of the number field. number, checkbox_field_id = 'field_uc2cq'; //Replace uc2cq with the field key of the Checkbox field. $(number_field_id).change(function(){ number = $(number_field_id).val(); if(number > 2){ //replace 2 with the value you want to check against document.getElementById(checkbox_field_id).checked = true; } else { document.getElementById(checkbox_field_id).checked = false; } }); }); </script>
Open a collapsible Section on page load
<script type="text/javascript"> jQuery( document ).ready( function( $ ){ $( '#frm_field_3575_container h3.frm_trigger' ).click();//Change 3575 to the id of your collapsible Section }); </script>
Change 3575 to the id of the collapsible Section you would like to open on page load.
Update a rich text field
This code example waits for a button click event to set the value to Value. A few things need to be checked in a rich text field, such as if the Visual Tab is open, if the text tab is open, and if TinyMCE has already been initialized.
<a id="set-rte-value">Click me</a> </script> const button = document.getElementById( 'set-rte-value' ); if ( button ) { button.addEventListener( 'click', handleButtonClick ); } function handleButtonClick() { if ( 'undefined' === typeof tinymce ) { return; } const rteFieldKey = 'pxcyh'; // Replace pxcyh with the KEY of the rich text field. const newValue = 'Value'; // Replace Value with the new value. const fieldIdAttribute = 'field_' + rteFieldKey; const editor = tinymce.get( fieldIdAttribute ); if ( editor && editor.getContentAreaContainer().closest( '.wp-editor-wrap' ).classList.contains( 'tmce-active' ) ) { editor.setContent( newValue ); } else { const textarea = document.getElementById( fieldIdAttribute ); if ( textarea) { textarea.textContent = newValue; } if ( editor ) { textarea.value = newValue; } } } </script>
Field Calculations
Conditional Calculation
Use this code to change the value of a field based on a selection in a dropdown field.
<script type="text/javascript"> Replace 3575 with the id of the collapsible Section you would like to open on page load. jQuery(document).ready(function($){ $('select[name="item_meta[125]"]').change(function(){ var val1 = $("select[name='item_meta[125]']").val(); if (val1 == 'Option 1') {$("#field_KEY").val('10.00');} else if (val1 == 'Option 2') {$("#field_KEY").val('20.00');} $("#field_KEY").change(); }); }); </script>
Replace 125 with the ID of your dropdown field and replace KEY with the field key of a text field in your form.
Reformat a calculated value
By default, values are calculated using a decimal. This will help you format the value differently for your currency.
<script type="text/javascript"> jQuery(document).ready(function($){ $('input[name="item_meta[988]"], input[name="item_meta[989]"]').change(function(){ var val = this.value; if (val !=undefined){ this.value = val.replace('.', ','); } }); }); </script>
Replace '988' and '989' with the field IDs of your calculation fields.
Truncate field
You can save part of the value of one field -- the first two letters, for example -- in another field. Replace wjque with your source field key and iyhhr with your destination field key. Replace 2 with the index of character where you want to the truncation to end. This end character won't be included in the truncation. If you want to truncate starting somewhere other than the first character, you can replace 0 with the place where you want to start. For more info, please see the substring documentation at MDN
<script> jQuery( document ).ready( function ( $ ) { var sourceField = '#field_wjqeu'; //replace wjque with your source field key var destinationField = '#field_iyhhr';//replace iyhhr with your destination field key $( sourceField ).change( function () { var sourceValue = $( sourceField ).val(); var truncated = sourceValue.substring( 0, 2 );//replace 2 with the index where you want to stop truncating $( destinationField ).val( truncated ); $( destinationField ).change(); } ); } ); </script>
Add comma-separated numbers
If you have a list of comma-separated numbers in one field, you can use this code to add them together and store the total in another field.
Change "prices" in #field_prices to the key of the field with the comma-separated numbers.
Change "total" in #field_total to the key of the field that will store the total of the numbers.
<script> jQuery(document).ready(function($){ $( '#field_prices' ).change( function () { var prices = $( '#field_prices' ).val(); var total = 0; if ( prices !== ''){ prices.split(', ').forEach(function (price) { total = total + parseInt( price ); }); } $( '#field_total' ).val( total ); $( '#field_total' ).change(); }); }); </script>
Get the maximum of comma-separated numbers
If you have a list of comma-separated numbers in one field, you can use this code to get the highest number and store it in another field.
Change "8t1yt" in #field_8t1yt to the key of the field with the comma-separated numbers.
Change "g900r" in #field_g900r to the key of the field that will store the maximum number.
<script> jQuery( document ).ready(function( $ ){ $('#field_8t1yt').change(function(){ // key of field with comma-separated values const valuesField = $( "#field_8t1yt" ).val(); // key of field with comma-separated values const stringArray = valuesField.split(','); const max = stringArray.reduce( ( highest, current) => { const currentNumber = parseInt( current, 10); return currentNumber > highest ? currentNumber : highest; } , stringArray[0]); $( "#field_g900r" ).val( max ); // field that stores the max value $( "#field_g900r").change(); // field that stores the max value }); }); </script>
Check if several fields have unique values
You can use this code to check if several text fields have unique values. In other words, you can check if each of the fields has a different value from the others. A separate field will store a certain word or phrase (e.g. 'unique') if the fields each have a different value. If there are some duplicates, this separate field will store a different value (e.g. 'has duplicates').
Change "#field_hcyj9, #field_y0lbc, #field_34f8v, #field_jz2pf, #field_6yvwp, #field_hi3be" to the fields you want to check for uniqueness. Each field is listed with "#field_" followed by the field's key.
Change "#field_vqifu" in two places to the field that holds the results value.
Change "unique" to the value you want to save if there aren't any duplicates among the fields.
Change "has duplicates" to the value you want to save if there are duplicates among the fields.
<script> jQuery( document ).ready( function ( $ ) { let fields = '#field_hcyj9, #field_y0lbc, #field_34f8v, #field_jz2pf, #field_6yvwp, #field_hi3be'; const fieldArray = fields.split( ', ' ); jQuery( fields ).change(function () { const fieldSet = new Set(); fieldArray.forEach(field => fieldSet.add(jQuery(field).val())); let answer = fieldArray.length == fieldSet.size ? 'unique' : 'has duplicates'; $( "#field_vqifu" ).val( answer ); $( "#field_vqifu" ).change(); }); }); </script>
Remove unwanted values
You can use this code to create a copy of a text field with unwanted values removed. For example, you can remove all instances of NOPE and MAYBE from a text field and save the result in another text field.
Please note that this will replace portions of words as well. So removing "in" will remove "in" everywhere, from win, inside, and ring, for example. The matching is case-sensitive, as written. So "NOPE" will match, but "nope" won't.
In a variation below, you can replace values with a preferred value.
To use on your site:
- Change "qhgxb" in two places to the key of the field with the original text.
- Change "r2ni7" in two places to the key of the field with the copy of the text, with unwanted values removed.
- Change "NOPE|MAYBE" to the values you want removed. Put a line (|) between each value, which stands for OR.
For more on regular expressions, see this MDN article on regular expressions in JavaScript.
<script> jQuery( document ).ready( function ( $ ) { $( '#field_qhgxb' ).change ( function () { //source field key var originalValue = $( "#field_qhgxb" ).val(); //source field key var cleanValue = originalValue.replace( /NO|MAYBE/g, '' ); $( "#field_r2ni7" ).val( cleanValue ); //destination field key $( "#field_r2ni7" ).change(); //destination field key }); }); </script>
Replace values
You can use this code to create a copy of text from a text field, with certain values replaced with another value. For example, you can create a copy of text with "red" and "blue" changed to "yellow."
Please note that this will change portions of words as well. Also, the matching is case-sensitive.
To use on your site:
- Change "qhgxb" in two places to the key of the field with the original text.
- Change "r2ni7" in two places to the key of the field with the copy of the text, with unwanted values removed.
- Change "red|blue" to the values you want removed. Put a line (|) between each value, which stands for OR.
Change "yellow" to the value you want as a replacement.
For more on regular expressions, see this MDN article on regular expressions in JavaScript.
<script> jQuery( document ).ready( function ( $ ) { $( '#field_qhgxb' ).change ( function () { //source field key var originalValue = $( "#field_qhgxb" ).val(); //source field key var newValue = originalValue.replace( /red|blue/g, 'yellow' ); $( "#field_r2ni7" ).val( newValue ); //destination field key $( "#field_r2ni7" ).change(); //destination field key }); }); </script>
Save user's timezone
You can use this code to save the user's timezone in a field in your form. Change '1238t' in two places to the key of the field in your form in which you want to save the user's timezone.
<script> jQuery(document).ready(function($){ $("#field_l238t").val(Intl.DateTimeFormat().resolvedOptions().timeZone); // Change '1238t' to the key of your field. $("#field_l238t").change(); // Change '1238t' to the key of your field. }); </script>
Copy address when checkbox is checked
If you'd like the user to be able to check a checkbox and have the billing address automatically copied to the shipping address, you can use the following code:
<script type="text/javascript"> jQuery(document).ready(function ($) { //change 1860 to the id of the checkbox used to copy the billing address to the shipping address $('input[name="item_meta[1860][]"]').change(function () { var billing = 'gnmo9',//change to the key of your billing address field shipping = 'jjlwy',//change to the key of your shipping address field sourceField, address_fields = ['line1', 'line2', 'city', 'state', 'zip'], country, country_billing, country_shipping; if ($(this).prop('checked')) { address_fields.forEach(function (field) { sourceField = $('#field_' + billing + '_' + field).val(); $('#field_' + shipping + '_' + field).val(sourceField); }); country_billing = $("select[id='field_" + billing + "_country']"); country_shipping = $("select[id='field_" + shipping + "_country']"); if (country_billing && country_shipping) { country = country_billing.val(); country_shipping.val(country); } } }); }); </script>
Replace 1860 with the ID of your checkbox field, replace gnmo9 with the key of your billing address field, and replace jjlwy with the key of your shipping address field. Please note that both address fields should both have the same Address Type for this snippet to copy all the fields properly.
Copy Date field as initial value
As a convenience for users, the date a user selects in one Date field can be copied to a second Date field. If the user has selected a date in the second Date field, it won't be changed.
<script type="text/javascript"> jQuery( document ).ready( function ( $ ) { var $firstDate = jQuery( '#field_first_date' ), $secondDate = jQuery( '#field_second_date' ); $firstDate.change( function () { var firstDateString = $firstDate.val(); var secondDateString = $secondDate.val(); if ( firstDateString === '' || secondDateString !== '' ) { return; } var firstDate = $firstDate.datepicker( 'getDate' ); firstDate.setDate( firstDate.getDate() ); $secondDate.focusin(); $secondDate.datepicker( "setDate", firstDate ); $secondDate.change(); } ); } ); </script>
Replace 'first_date' with the key of the first date field and 'second_date' with the key of the second date field. So if the key to your first date field is kt0v7, the full id would be: '#field_kt0v7'.
Save character count in another field
You can use this code example to save in one field the number of characters that are in another field.
<script> jQuery( document ).ready( function ( $ ) { $( '#field_l4608' ).keyup( function () { // Change l4608 to the main field's key. var characters = this.value; var characterCountField = $('#field_wy5zr'); // Change wy5zr to the character count field's key. characterCountField.val( characters.length ); // characterCountField.change(); } ); } ); </script>
Calculate time difference
Use this code to calculate the difference between two time fields. Replace hlbr1 with the key of the first Time field. Replace 5v5lu with the key of the second Time field. Replace j16i2 with the key of the Text field where you are displaying the time difference.
<script type="text/javascript"> jQuery(document).ready(function($){ $('#field_hlbr1,#field_5v5lu').change(function(){ var start_time = $("#field_hlbr1").val(); var end_time = $("#field_5v5lu").val(); end_time = end_time.slice(0,5); start_time = start_time.slice(0,5) if(start_time !="" && end_time !=""){ start_time = start_time.split(":"); end_time = end_time.split(":"); var startDate = new Date(0, 0, 0, start_time[0], start_time[1], 0); var endDate = new Date(0, 0, 0, end_time[0], end_time[1], 0); var diff = endDate.getTime() - startDate.getTime(); var hours = Math.floor(diff / 1000 / 60 / 60); diff -= hours * 1000 * 60 * 60; var minutes = Math.floor(diff / 1000 / 60); minutes = (minutes < 9 ? "00" : minutes); console.log(hours + ":"+minutes); $("#field_j16i2").val(hours + ":"+minutes); $("#field_j16i2").change(); } }); }); </script>
Get the total of comma separated values
Use this code example to sum the total values retrieved using a Checkbox Lookup field.
- Add a hidden field to the form to retrieve the numeric value.
- The hidden field should watch your checkbox field.
- Add a separate field to show the total for selected checked items.
<script type="text/javascript"> jQuery(document).ready(function($){ $('#field_qgx3g').change(function(){ //Change qgx3g to the key of the hidden field added to your form var total=0; var nums = $("#field_qgx3g").val().split(","); //Change qgx3g to the key of the hidden field added to your form for (var i = 0; i < nums.length; i++) { total += parseInt(nums[i]); } $("#field_rq0dk").val(total); //Change rq0dk to the key of the visbile field added to your form $("#field_rq0dk").change(); //Change rq0dk to the key of the visbile field added to your form }); }); </script>
Copy and concatenate field values
Please note: This is a built-in feature as of version 2.02. Read more about it here.
You may want to combine two strings of text or a string of text with a number in your form. For example, you may have one field where the user enters their first name and another where they enter their last name, but you would like to display the first and last name together in another field. This type of calculation is not built-in, but you may follow these directions to set it up manually.
Text fields
If you are combining text fields, use the following code.
<script type="text/javascript"> jQuery(document).ready(function($){ $('#field_key1, #field_key2').change(function(){ var val1 = $("#field_key1").val(); var val2 = $("#field_key2").val(); $("#field_keytotal").val(val1+' '+val2); $("#field_keytotal").change(); }); }); </script>
Replace 'key1' and 'key2' with the field keys of the two fields to be combined. Replace 'keytotal' with the field key for the total field.
If you are copying text entered into one field into another, use this code:
<script type="text/javascript"> jQuery(document).ready(function($){ $('#field_abcd').change(function(){ //source field key var sourceField = $("#field_abcd").val(); //source field key $("#field_wxyz").val(sourceField); //destination field key $("#field_wxyz").change(); //destination field key }); }); </script>
Replace 'abcd' with the field key of the source field, and 'wxyz' with the field key of the destination field.
Embedded fields
If you are copying text entered in one field outside an embedded form into a field inside an embedded form, use this code:
<script type="text/javascript"> jQuery(document).ready(function($){ $('#field_abcd').change(function(){ //source field key var sourceField = $("#field_abcd").val(); //source field key $("#field_wxyz-0").val(sourceField); //destination field key $("#field_wxyz-0").change(); //destination field key }); }); </script>
Replace 'abcd' with the field key of the source field, and 'wxyz' with the field key of the destination field.
Radio buttons
If you are combining radio button fields, use the following code.
<script type="text/javascript"> jQuery(document).ready(function($){ $('input[name="item_meta[988]"], input[name="item_meta[989]"]').change(function(){ var val1 = $("input[name='item_meta[988]']:checked").val(); var val2 = $("input[name='item_meta[989]']:checked").val(); if (val1 !=undefined && val2 != undefined) {$("#field_keytotal").val(val1+' '+val2);} }); }); </script>
Replace '988' and '989' with the field IDs of your radio buttons. Replace 'keytotal' with the field key of your total field.
Dropdown fields
If you are combining dropdown fields, use the following code.
<script type="text/javascript"> jQuery(document).ready(function($){ $(document).on('change', 'select[name="item_meta[994]"], select[name="item_meta[995]"]', function(){ var val1 = $("select[name='item_meta[994]']").val(); var val2 = $("select[name='item_meta[995]']").val(); $("#field_keytotal").val(val1+' '+val2); }); }); </script>
Replace '994' and '995' with the field IDs of your dropdowns. Replace 'keytotal' with the field key of your total field.
To copy the selected value from one Dropdown field to another, use the following code.
<script type="text/javascript"> jQuery( document ).ready( function( $ ) { $( document ).on( 'change', 'select[name="item_meta[4417]"]',function() { const val = $( "select[name='item_meta[4417]']" ).val(); $( "#field_xbeaq" ).val( val ); }); }); </script>
Replace '4417' with the field id of the first Dropdown in two places. Replace 'xbeaq' with the field key of the second Dropdown.
Checkboxes
If you are combining checkbox fields, use the following code.
<script type="text/javascript"> jQuery(document).ready(function($){ $('input[name="item_meta[453][]"], input[name="item_meta[455][]"]').change(function(){ var val1 = $("input[name='item_meta[453][]']:checked").map(function () { return this.value; }).get().join(","); var val2 = $("input[name='item_meta[455][]']:checked").map(function () { return this.value; }).get().join(","); $("#field_keytotal").val(val1 + ' ' + val2); }); }); </script>
Replace '453' and '455' with the field IDs of your checkboxes. Replace 'keytotal' with the field key of your total field. If you would like to join your checkbox values with something other than a comma, just replace the comma in join(",") with any character.
Repeaters
If you need to copy text from a text field in your form into a text field within a repeater in your form, use the following javascript:
<script type="text/javascript"> document.addEventListener("DOMContentLoaded", function(event) { copyValueToRepeat(); var sourceField = document.getElementById( 'field_j8dihw' ); sourceField.addEventListener( "change", function(event) { copyValueToRepeat(); }); }); jQuery(document).on('frmAfterAddRow', copyValueToRepeat ); function copyValueToRepeat(){ var sourceField = document.getElementById( 'field_j8dihw' ); var repeatFields = document.querySelectorAll( '.frm_field_240_container input'); for ( var i = 0, len=repeatFields.length; i<len; i++ ) { repeatFields[i].value = sourceField.value; } } </script>
Replace j8dihw (in two places) with the field key of your source field and replace 240 in .frm_field_240_container with the field id of the text field within the repeater.
Note: Field keys and IDs are different. If you cannot get this javascript to work, double check to make sure you're using the key when needed and the ID when needed.