Custom JavaScript Action
The Custom Javascript action allows you to execute custom JavaScript when an action is run. While most actions do not require any programming, the Custom Javascript action requires Javascript programming and enables you to extend your form's functionality.
Adding a Custom JavaScript Action
Follow these steps to add the action:
- In the Actions window, click the New item in the toolbar at the top of the window.
- In the New Action Settings window, choose Custom JavaScript from the drop-down menu and click Next.
- In the Action Name field, give your action a unique name.
- If you are editing an action for an element / field, choose the Field Event on which you want the action to trigger: when the user changes (Change), enters (Enter), or leaves (Leave) the field.
- Click the Rule button to configure one or more rules that must be satisfied before the action will run.
- Configure the Confirmation Settings to show a confirmation prior to submitting the form. The confirmation prompt will be shown before the action is executed and the end user may choose OK to execute the action or Cancel to abort.
- Click Next to move to the next step, where you can work with the form and field objects. The form object has a number of methods/functions available and the most common one is targeting a field using its name(getFieldByName) so you can call methods on that field object. Some examples are listed below.
- Click Finish to close this window and return to the Actions window.
-
Click Save to return to the Form Designer and preview your form to test the action.
Examples of JavaScript
To set/get the value of a field:
form.getFieldByName('nameOfField').setValue('anyValue'); form.getFieldByName('nameOfField').getValue();
To hide/show a field:
form.getFieldByName('nameOfField').hide(); form.getFieldByName('nameOfField').show();
Custom Formatting.
Custom JavaScript actions on a field's leave event can be used to format the data entered in the field.
Capitalize first letter of each word:
function(field,form) { var str = field.getValue(); var splitStr = str.toLowerCase().split(' '); for (var i = 0; i < splitStr.length; i++) { splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); } field.setValue( splitStr.join(' ') ) }
Capitalize first letter of first word only:
function(field,form) { var str = field.getValue(); field.setValue( str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() ); }
Convert a numeric dollar value to a Word
This action JS should be attached to the field with the numeric dollar value and should be set to run on the change event. Add a another field named 'formattedValue' to hold the output. A value like '10,000' will be converted to 'Ten Thousand'
// This function will receive the field and form objects. function(field,form){ var th = ['','thousand','million', 'billion','trillion']; var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine']; var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen']; var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; function toWords(s) { s = s.toString(); s = s.replace(/[\, ]/g,''); s = s.replace(/\$/g,''); if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return 'too big'; var n = s.split(''); var str = ''; var sk = 0; for (var i=0; i < x; i++) { if ((x-i)%3==2) { if (n[i] == '1') { str += tn[Number(n[i+1])] + ' '; i++; sk=1; } else if (n[i]!=0) { str += tw[n[i]-2] + ' '; sk=1; } } else if (n[i]!=0) { // 0235 str += dg[n[i]] +' '; if ((x-i)%3==0) str += 'hundred '; sk=1; } if ((x-i)%3==1) { if (sk) str += th[(x-i-1)/3] + ' '; sk=0; } } // add 'dollars' if (str){ str += ' dollars' } var sourceCents = s.split('.'), sourceCents = sourceCents[sourceCents.length-1], cents=''; if (sourceCents[0] == 0 && sourceCents[1] == 0){ return str.replace(/\s+/g,' '); }else if (sourceCents[0] == 0 && sourceCents[1] != 0){ cents += dg[sourceCents[1]] +' '; }else if (sourceCents[0] == 1){ cents += tn[sourceCents[1]] +' '; }else{ cents += tw[sourceCents[0]-2] + ' ' + dg[sourceCents[1]] + ' '; } if (cents){ if (str){ str += ' and' } str += ' ' + cents + ' cents' } var strformatted = str.replace(/\s+/g,' '); return strformatted.charAt(0).toUpperCase() + strformatted.slice(1); } form.getFieldByName('formattedValue').setValue(toWords(field.getValue().replace('$',''))) }
Storing last-four digits of credit card numbers.
Credit card numbers are encrypted and not visible in the Logiforms database. If you want to grab the last four digits on the form and store them separately, here is how to do that.
Replace the form's Submit button with a Single Button element and hide the original submit button Add an action to the new submit button, choose Custom JavaScript action and use the following code. Note, it may need to be modified based on the names of the fields on your form:
// This function will receive the field and form objects. function(field,form){ var cardnum = form.getFieldById('ccnumber').getValue(); var last4 = cardnum.substr(cardnum.length-4,cardnum.length-1) var str = '****' + last4; form.getFieldByName('last4').setValue(str) }
Finally, add another action after that action that will submit the form.
The first action will parse the last 4 digits of the card and store them in a field named 'last4' (note you need to have a field named last4 on your form or you can modify the fieldname used in the script), and the second action will submit the form.
Generate a Unique ID and write it to a field on your form
// This function will receive the field and form objects. function(field,form){ // this function generates the unique ID var guid = function() { var s4 = function() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + s4() + s4() + s4()+ s4()+ s4()+ s4()+ s4(); } // write the unique ID to a field named UUID form.getFieldByName('UUID').setValue(guid()) }
Simple Random Number Generator
// This function will receive the field and form objects. function(field,form){ // this function generates a 5 digit random number var randomnum = Math.floor(Math.random() * 90000) + 10000; // write the random number to a field named 'myrandomnumber' form.getFieldByName('myrandomnumber').setValue(randomnum) }
Count the number of selected options
This action will count a comma seperated list of values (which is how drop downs, radios, and checkboxes store their values), and write the total to another field. This action should be attached to the change event of the field being counted.
// This function will receive the field and form objects. function(field,form){ // count the number of items var total = field.getValue().split(',').length; // and write to 'TotalForms' field form.getFieldByName('TotalForms').setValue(total); }
Form Actions
Form Actions are attached to the Forms Root Node and run when the form first loads.
Hide Progress Bar on a Specific Page of a Multi Page Form
/// This function will receive the field and form objects. function(field,form){ //hide on first page form.mp.navigator.pi.hide(); form.mp.eventMgr.addListener('pagechange',function(mp,newpage,oldpage){ // hide condtionally on each page load if (newpage.name == 'StartPage'){ mp.navigator.pi.hide(); }else{ mp.navigator.pi.show(); } }); }
Move the Progress bar below the top heading or logo.
This code is configured to run the forms "pageChange" event. It attaches a listener to that event and then moves the Progress Bar from the very top of the page to below the first child element on the page.
/// This function will receive the field and form objects. function(field,form){ form.mp.eventMgr.addListener('pagechange',function(mp,newpage,oldpage){ $('.progress').insertAfter($($('#page_'+newpage.id).children().get(0))) }); }
Move the Progress bar to the bottom of the page above the buttons
/// This function will receive the field and form objects. function(field,form){ // move on first page var page = $('#page_'+form.mp.pages[0].id); var buttonBar = $($('.btn_bar',page)[0]); $('.progress').insertBefore(buttonBar) // move on other pages form.mp.eventMgr.addListener('pagechange',function(mp,newpage,oldpage){ var page = $('#page_'+newpage.id); var buttonBar = $($('.btn_bar',page)[0]); $('.progress').insertBefore(buttonBar) }); }
Select all Checkboxes
This action will check al checkboxes in the field names "MyData"
// This function will receive the field and form objects. function(field,form){ var allselections = [], myfield = form.getFieldByName('MyData'); myfield.getEl().each(function(a,b){ allselections.push($(this).val()) }); myfield.setValue(allselections.join()) }
Select all Checkboxes after returning Dynamic Data
This action will check al checkboxes in the field names "MyData", which has dynamically loaded data. This is similar to the above action, but this action listens to the Dynamic Data load event.
Important!
This action must be set on the forms root node as a "Form" action so that it runs when the form is loaded.// This function will receive the field and form objects. function(field,form){ var myfield = form.getFieldByName('MyData'), allselections=[]; // listen for the dynamic data load event myfield.dynamicMgr.eventMgr.addListener( 'load', function(dd,result){ if (!dd.isRunning){ var doPop = function(myfield,allselections){ myfield.getEl().each(function(a,b){ allselections.push($(this).val()) }); myfield.setValue(allselections.join()) } doPop.defer(200,this,[myfield,allselections]) } }, this ) }
Auto Submit Form Action with Delay
This action will automatically submit the form after the delay specified:
// This function will receive the field and form objects. function(field,form){ var dosubmit = function(form){ lfform.submit(true) } dosubmit.defer(1000,this,form) }
Run the Change Event on a Field
This can be useful to trigger the change event on a field and force any bindings that reference that field to run. Attach this to the forms submit button for example, to force a binding to run prior to the form being submitted, even if the field value did not change. In this example, we get the ID of the field named "CITY" and trigger its change event to run.
// This function will receive the field and form objects. function(field,form){ form.triggerFieldEvent(form.getFieldByName('CITY').id,null,true); }
0 Comments