Adding Title/Suffix Inputs into Name Fields on Forms

My client had the need to include a title and suffix for a registered person in their app for legalities.
Knack currently offers a few display formats for name fields, but not one that allows for free text titles, and no suffix option.
I could easily have just added a separate title and suffix field and left it at that, but I thought I’d have a crack at merging them all in the same row with a bit of JavaScript.

image

Procedure:

  1. Add Title (short text), Suffix (short text), and Name (name) fields
    Take note of your field keys for these three.

  2. Add a Full name (text formula) field with the formula:
    trim({Title} {Name} {Suffix})

  3. On every form in your app that allows for an editable name, make sure to include the Title and Suffix fields
    image

  4. Insert the following code snippet into the JavaScript editor, and replace the field_xx, field_yy, and field_zz with your three name fields:


  var nameField = "field_xx"
  var fieldIDs = {
    Title: "field_yy",
    Suffix: "field_zz",
  };
  var $nameGroup = $(`div#kn-input-${nameField} .control.is-grouped`)

  // Iterate through the fields (title, suffix)
  for (var field in fieldIDs) {
    var $fieldDiv = $(`div#kn-input-${fieldIDs[field]}`);
    var $fieldLabel = $fieldDiv.find('label');
    var $fieldInstruction = $fieldDiv.find('p');
    var $fieldInput = $fieldDiv.find('div input');
    var $fieldControl = $('<p class="control is-expanded">');

    /* Remove labels and instructions and add placeholder text to field */
    $fieldLabel.remove();
    $fieldInstruction.remove();
    $fieldInput.attr('placeholder', field);
    $fieldControl.append($fieldDiv);

    /* Append or prepend field to name group */
    field === 'Title' ? $nameGroup.prepend($fieldControl) : $nameGroup.append($fieldControl);
  }

  /* Remove any empty controls, and adjust the flex of the first, middle, and last controls */
  var $nameFields = $('div.control.is-grouped').find('p.control.is-expanded');
  $nameFields.filter(':empty').remove(); 
  $nameFields.first().css('flex', '1'); 
  $nameFields.last().css('flex', '1');
  $nameFields.not(':first-child, :last-child').css('flex', '2');

});

Once applied, the script will run on each form view render, clear out any labels/instructions, add placeholder texts, add the Title field before, add the Suffix field after, and adjust the flex of the fields.

Note that is only applicable on Form views, and will not work for inline editing forms.

2 Likes