Assign the source property of the Handsontable dropdown option to match the related data value

I received a dynamic data array through an ajax call:

    data=[ // values are subject to change
        ['Alex', '16', ['2024-01-01,50000', '2024-03-01,20000', '2024-05-01,30000']],
        ['Bob', '21', ['2022-02-01,50000', '2022-03-01,10000']],
        ['Jack', '20', ['2023-03-01,50000', '2023-04-01,60000', '2023-05-01,50000']],
        ['John', '18', ['2020-04-01,20000', '2020-05-01,50000', '2020-06-01,30000', '2020-07-01,50000']],
    ];

I am looking to create a dropdown for the third column that represents dates and amounts in each option using basic JavaScript.

While it would be simple if the data was static, since it is fetched dynamically via ajax, I cannot hardcode the source property of the dropdown menu.

This involves initialization with plain JavaScript Handsontable.

Any assistance on this matter would be highly appreciated.

I have implemented a getSource function with query and callback parameters in the source attribute like so:

    function getSource(query, callback) {
        var selectedRow = hotInstance.getSelected()[0][0];
        var options = data[selectedRow][2];
        callback(options);
    }

However, I encountered an issue where selecting an option from the dropdown update its content. For instance, when choosing an option (let's say '2024-03-01,20000') from the first row dropdown, upon reopening the dropdown, the displayed items show '2024-03-01' as the first entry and '20000' as the second instead of displaying all three options: '2024-01-01,50000', '2024-03-01,20000', '2024-05-01,30000'.

Answer №1

Does this solution meet your needs?

const container = document.querySelector('.result');
const table = document.querySelector('.ht');
const API_URL = 'https://randomuser.me/api/?results=10';
let hotTable, responseData;

responseData = [
  {
    "First name": "Emma",
    "Last name": "Garcia",
    "E-mail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e7efefe3ace5e3f0e1ebe3c2e7fae3eff2eee7ace1edef">[email protected]</a>",
    "Country": "United States"
  },
  {
    "First name": "Noah",
    "Last name": "Hernandez",
    "E-mail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117f7e70793f7974637f707f75746b517469707c617d743f727e7c">[email protected]</a>",
    "Country": "Canada"
  },
  {
    "First name": "Olivia",
    "Last name": "Gomez",
    "E-mail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="482724213e2129662f27252d32082d30292538242d662b2725">[email protected]</a>",
    "Country": "Mexico"
  }
]  

hotTable = new Handsontable(table, {
    data: responseData,
    colHeaders: ['First name', 'Last name', 'E-mail', 'Country'],
    rowHeaders: true,
    colWidths: [100, 100, 200, 150],
    licenseKey: 'non-commercial-and-evaluation'
});

fetch(API_URL)
.then(response => {
    if(response.ok){
    return response.json()
  }
})
.then(data => {
  let nameData = data.results.map( person => (
     person.name.first
  ))
  console.log(nameData)
  hotTable.updateSettings({
     cells: (row, col) => {
      let cellProps = {}
      if(col === 0){
        cellProps.type = 'dropdown';
        cellProps.source = nameData;
      }
      return cellProps;
    }
  })
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...

Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Eve' } ] My goal is to locate an object by its id and append a ...

Passport JS receiving negative request

I'm currently experiencing an issue with the passport req.login function. When a user logs in using their email and password, instead of redirecting to /productos2 as intended, it routes to a bad request page. I am utilizing ejs and mongoose for this ...

Determine the precise x and y coordinates of a centered element using JQuery

How can I determine the exact left and top positions of an element? The parent container has text-align: center, causing potential confusion when there are multiple elements on the bottom row. For instance, the first one may have a position of 0px instea ...

Is it possible to modify the stroke color of the progress circle in ng-zorro?

I am working on an Angular project where I aim to create a dashboard displaying various progress circles. Depending on the progress, I need to change the color of the line. Current appearance: https://i.sstatic.net/hR2zZ.png Desired appearance: https://i. ...

Best practices for retrieving a PHP variable without the need to submit a form using AJAX

I'm a beginner with AJAX I'm trying to achieve something similar to this: $query="select name from login_master where name=txtName.value();"; //txtName refers to a textbox. Is it possible to accomplish this using AJAX without submitting the fo ...

How to use the route.navigate() method in Angular 9 to open a URL in a new tab with a query string

When a button is clicked within a table in our application, I have to open a new tab with details of a specific record from the table. Currently, the code I am using navigates to a new URL and uses resolvers to fetch data from the backend on the new page. ...

Picture in the form of a radio button

Is there a way to use an image instead of a radio button in my AngularJS form? I have managed to hide the radio button using CSS, but it disables the checked event. How can I make the image clickable? position: absolute; left: -9999px; Here is the code s ...

Ways to programmatically compare all elements between two separate arrays

Is there a way to create a process where the first loop iterates through the elements of one array, while another loop goes through a second array and compares each element in the first array with all elements in the second array? For example: //first loo ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...

The function of window.location is a mixed bag of success and failure

I am encountering an issue with a JavaScript function that is supposed to navigate to the next page when clicking a button. The function works correctly for step 1, but it fails for step 2. Upon executing the function using nextstep = 'form', _b ...

Specify "Accept" headers using jQuery when fetching data within an iframe

I am working on a webpage where I am adding an iframe dynamically like this: $('<iframe id="testIframe" />').src('http://www.google.nl/').appendTo('body'); The accept headers being sent while loading the content in thi ...

Arrange the Json array by key value in a different order

I have a contact list that is returning in a lengthy form, organized based on order of entry. I am looking to alphabetically sort the list by displayName which is nested within the main array. Can anyone assist with this challenge using JavaScript? Thank ...

Click the link to find the JSON node that corresponds to the onclick event

After parsing JSON, the JS code below is returning a list of movie titles for me. Each movie title node contains additional attributes and values that are not currently being displayed. My goal is to have the other values in that specific node displayed wh ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...

When validating with Sequelize, an error occurred due to one or more columns being undefined:

Hello everyone, I'm facing some issues. Can anyone explain why this.day_number and this.teacher_id are coming up as undefined? 'use strict' module.exports = (sequelize, DataTypes) => { const Teacher = sequelize.models.teachers ...

Cease all playback of audio immediately

My goal is to ensure that any audio that has been played previously stops before a new audio clip starts playing. This will prevent overlapping clips on elements that may trigger the audio file multiple times. I have attempted to pause and reset the curre ...

Error in TypeScript: The property 'data' is not found within type '{ children?: ReactNode; }'. (ts2339)

Question I am currently working on a project using BlitzJS. While fetching some data, I encountered a Typescript issue that says: Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339) import { BlitzPage } from &q ...

Exploring the capabilities of batch updates in Firestore with the latest web version-9

I am facing issues when trying to update certain values in my firestore collection within my nuxt project. const batch = writeBatch(firestore); const data = query(collection(firestore, `notifications`, `${uid}/news`)); const querySnapshot = await ...