Full Name to First and Last Name Fields
This vanilla Javascript will to split a Full Name Field into the system First Name and Last Name Fields.
Change Log
- v1.1.0 - Made field ID's unique by appending form alias and changed regular `window.onload` to an `addEventListener`. These changes are to allow for multiple forms on the same page.
-
Add a dummy Full Name Field in your form layout (NOT the form builder).
Note: This is a client side script, so you cant delete the first and last name fields from your form configuration. So make sure you still have at least the First Name and Last Name fields in your form setup in the admin form builder.
{% comment %}<!-- Treehouse CODE v1.1.0 -->{% endcomment %} <label for="FullName{{this.Alias}}">Full Name</label> <input type="text" id="FullName{{this.Alias}}" name="FullName" >
-
Hide the First and Last name fields in your form layout (don't delete them).
Also, update their ID's (and any corresponding form lables) to include the forms alias. This ensures these fields are unique if you have multiple forms on the same page.{% comment %}<!-- Treehouse CODE v1.1.0 -->{% endcomment %} <div style="display: none;"> <label for="FirstName{{this.Alias}}">First Name</label> <input type="text" id="FirstName{{this.Alias}}" name="FirstName" ><br> <label for="LastName{{this.Alias}}">Last Name</label> <input type="text" id="LastName{{this.Alias}}" name="LastName" ><br> </div>
-
Add the following script below your form.
//## Treehouse CODE v1.1.0 ## <script> window.addEventListener("load",function(){ // assign fields to variables var fullNameField = document.getElementById('FullName{{this.Alias}}'); var firstNameField = document.getElementById('FirstName{{this.Alias}}'); var lastNameField = document.getElementById('LastName{{this.Alias}}'); //Once the user has tabbed out of the field fullNameField.addEventListener('blur', function() { //Get the field value, assign it to an array then apply the 1st word to the First name Field. var fullNameFieldArray = this.value.split(" "); firstNameField.value = fullNameFieldArray[0]; //remove the first item from the array fullNameFieldArray.shift(); //Apply remaining array to Last Name Field as a string seperated by a space. lastNameField.value = fullNameFieldArray.join(" "); }); },false); </script>
Comments or questions? Head over to the Treepl CMS forum to discuss with the community.