Dynamically Add Rows to Tables
Overview
This article introduces how to add rows to a table using JavaScript. An Add button is placed inside the record. Clicking the button adds a new row to the end of the table, by pushing data into the end of the table array.
Initial Setup
This section describes building a Kintone App before adding rows to a table.
Create a sample App
First, create a new Kintone App.
Set the fields in the sample App as follows.
| Field Type | Field Name | Field Code |
|---|---|---|
| Text | Company Name | company_name |
| Blank space | Add Contact | add_contact |
| Table | Contact List | contact_list |
Set the fields inside the Table field as follows.
| Field Type | Field Name | Field Code | Notes |
|---|---|---|---|
| Text | Contact Name | contact_name | |
| Link | Email Address | email_address | Select E-mail address as the type |
| Check box | Mailing List | mailing_list | Add two options: "Newsletter" and "Product Updates". |
Create sample data
Next, add a record, and enter three rows of sample data into the table as shown below:
| Contact Name | Email Address | Mailing List |
|---|---|---|
| Emma Rivera | emma.rivera@example.com | Newsletter |
| Noah Chen | noah.chen@example.com | Product Updates |
| Olivia Park | olivia.park@example.com | Newsletter |
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
.
|
|
Save the settings and click Update App. Open a record and click Edit record. An Add button appears on the Space field.
Click the Add button to add a new row to the end of the "Contact List" field.
Code Explanation
This section explains the sample code above.
Create a Button in the Space Field
The app.record.create.show and app.record.edit.show events run when the Add record screen or Edit record screen is displayed.
kintone.app.record.getSpaceElement('add_contact') retrieves the Space element by its element ID, add_contact. A button labeled Add is created and appended to that element. The addRow function is assigned to the button's onclick event.
|
|
Add a Row to the Table
kintone.app.record.get() retrieves the record data.
The Table field is represented as an array, so push() adds a new element to the end of the array. Each field code inside the row requires a type and a value. The Check box value is specified as an array.
|
|
Finally, kintone.app.record.set() reflects the updated record data on the screen.
|
|
Notes
The new row of data is added when the Add button is clicked.
To add a row when the record is saved instead, use a different approach. Edit the table data in the record object passed to the app.record.create.submit.success or app.record.edit.submit.success event, and return the event object. The edited table data is then reflected in the record.