Add Leading Zeros to Numbers

Contents

Overview

This article introduces how to lead a number with 0s in a field of a Kintone App.

Sample Image

An event is triggered when the focus leaves the Number field while creating or editing a record. 0s are added to the beginning of the number until it reaches a fixed digit length. The result is inserted into the Result field.

Prepare the App

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

Field Type Field Name Field Code
Number Number number
Text Result result

Sample Code

Prepare the following JavaScript code in a text editor and navigate to the Kintone App's settings. Upload the file into the Upload JavaScript for PC option of 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
(function() {
  'use strict';
  var NUMBER = 'number'; // field code of number field
  var ZEROFILL = 'result'; // field code of text field to set result into
  var NUMOFDIGITS = 8; // number of digits for the result

  function zeroFill(value, length) {
    if (value.length >= length) {
      return value;
    }
    return (new Array(length).join('0') + value).slice(-length);
  }

  var events = ['app.record.create.change.' + NUMBER, 'app.record.edit.change.' + NUMBER];

  kintone.events.on(events, function(event) {
    var record = event.record;
    var changes = event.changes.field;
    var length = NUMOFDIGITS;
    record[ZEROFILL].value = zeroFill(changes.value, length);
    return event;
  });
}());

After saving the settings and clicking on Update App, create a new record. Fill in the Number field with numbers, and take the focus off the field. A version of the number leaded with 0s should be inserted into the Result field.