Count Characters Inside Fields

Contents

Overview

This sample code counts the number of characters in a Text in Text area field. Spaces in the text field are excluded from the count. The final count value is set into a Number field.

Sample Image

The number of characters are counted upon saving the record. The Number field is also un-editable when creating or editing the record.

Animated GIF: A Kintone record being saved, and the number of characters being automatically entered into a number field.

Prepare the App

Create an App (External link) including the following fields and settings.

Field Type Field Name Field Code
Text or Text area Body body
Number Number of Characters count

Sample Code

Prepare the following JavaScript code in a text editor and navigate to the Kintone App’s settings. Upload the file into the JavaScript and CSS Customization settings (External link).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Count number of characters in the text field and set it in the number field
(function() {
  'use strict';
  var BODY = 'body'; // field code of text or text area field
  var COUNT = 'count'; // field code of number field

  kintone.events.on(['app.record.create.submit', 'app.record.edit.submit', 'app.record.index.edit.submit'], function(event) {


    // Obtain characters in the text field
    var record = event.record;
    var string = record[BODY].value;
    // If the number of characters is zero, put zero in number field and return
    if (!string) {
      record[COUNT].value = 0;
      return event;
    }
    // Remove spaces
    var string2 = string.replace(/\s+/g, '');

    // Enter character count into number field
    record[COUNT].value = string2.length;

    return event;
  });
})();

After saving the settings and clicking on Update App, create a new record in the App. Enter some characters into the Body field, and save the Record. The number of characters should be inserted into the Number of Characters field.