Skip to main content
All CollectionsGetting Started
[Workaround] JavaScript for Multi-Choices in Glide
[Workaround] JavaScript for Multi-Choices in Glide

How to use JavaScript column to have different values of choices

Updated today

Introduction

The Choice component in Glide allows users to select a single value based on predefined options. However, if you need different values to be derived from multiple selected choices, you can achieve this functionality using a JavaScript column.

This guide explains how to implement this workaround step-by-step, enabling dynamic value mapping for multi-choice selections.


Steps to Implement

1. Prepare Your Data

  1. Add a Text Column

    • In a separate table, create a text column to store the choice values.

    • Populate this column with the desired choice options (e.g., "Choice 1", "Choice 2").

  2. Add a Text Column for Results

    • Create another text column in the same table to capture the user's selected values.


2. Configure the Choice Component

  1. In your app layout, add a Choice Component.

  2. Link this component to the text column for user selections.

  3. Use the first column (choice values) as the source for the choice options.

  4. Enable Allow Select Multiple in the component settings.

Result:
The selected choices will be stored in the result column, separated by commas (e.g., Choice 1, Choice 2, Choice 4).


3. Add a JavaScript Column

Create a JavaScript column in your table and paste the following code:

// Define the mapping of choices to values
const choiceValues = {
"Choice 1": 1,
"Choice 2": 2,
"Choice 3": 3,
"Choice 4": 4,
"Choice 5": 5
};

// Initialize an empty array to store matched values
let matchedValues = [];

// Split the selections in p1 and p2 into arrays (remove extra spaces)
let p1Choices = p1.split(',').map(choice => choice.trim());
let p2Choices = p2.split(',').map(choice => choice.trim());

// Iterate over the user-selected choices in p2
p2Choices.forEach(choice => {
// Check if the current choice in p2 exists in p1
if (p1Choices.includes(choice)) {
// Push the corresponding value from the mapping if it exists
if (choiceValues[choice]) {
matchedValues.push(choiceValues[choice]);
}
}
});

// Return the matched values, joined as a string
return matchedValues.join(', ');

4. Adjust the choiceValues Object

In the code snippet, the choiceValues object maps each choice to a corresponding value.

Examples:

  • If the value needs to be a string, use quotes:

    "Choice 1": "Value 1"
  • If the value is a number, no quotes are needed:

    "Choice 1": 1

This flexibility allows you to tailor the mapping to suit your specific needs.


5. Test the Setup

Once the JavaScript column is set up:

  1. Select multiple choices in the app.

  2. Observe that the JavaScript column dynamically returns the mapped values as a comma-separated string.


Example Template

For a practical example, you can access the template here:

Did this answer your question?