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.

  1. 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.

    <!--Treehouse CODE v1.0.0-->
    <label for="FullName">Full Name</label>
    <input type="text" id="FullName" name="FullName" >
  2. Hide the First and Last name fields in your form layout (don't delete them).

    <!--Treehouse CODE v1.0.0-->
    <div style="display: none;">
      <label for="FirstName">First Name</label>
      <input type="text" id="FirstName" name="FirstName" ><br>
      <label for="LastName">Last Name</label>
      <input type="text" id="LastName" name="LastName" ><br>
  3. Add the following script below your form.

    <!--Treehouse CODE v1.0.0-->
    window.onload = function() {
    	// assign fields to variables
    	var fullNameField = document.getElementById('FullName');
    	var firstNameField = document.getElementById('FirstName');
    	var lastNameField = document.getElementById('LastName');
    	//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
    		//Apply remaining array to Last Name Field as a string seperated by a space.
    		lastNameField.value = fullNameFieldArray.join(" ");

Comments or questions? Head over to the Treepl CMS forum to discuss with the community.