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 Pro.
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]']
- 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
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 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.
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
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 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.
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"> 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.
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.
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.
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>
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'.