Sending a two-dimensional array between JavaScript functions

When trying to gather information from a user using a 2D array in Javascript, I am encountering an issue with passing the array from one function to another as an actual array rather than text. What am I doing wrong?

The specific array looks like this:

Title       Category1   Category2   Category3
Category1   Apples      Blue        Eyes
Category2   Oranges     Green       Legs
Category3   Pairs       Yellow      Arms
            Mango       Gray    

The goal is to display `Column1` first by showing the "Title" as text and the Categories as buttons. When a button is clicked, it should show the contents of that column. For example, clicking on Category3 should display Category3 as text and the options "Eyes", "Legs", and "Arms" as buttons.

The issue arises when passing the correct parameters in the `onclick` event. Using `nextStep(this,database)` does not work as expected. If I try `nextStep(this,\''+database+'\')`, it passes the database as text instead of an array.

Any suggestions on how to solve this problem?

The HTML structure is simply a div:

<div id="mainPage"></div>

The JavaScript code starts on page load:

window.addEventListener("load", starting, false);

function starting(){
  var database = [[Title, Category1, Category2, Category3], [Category1,Apples,Blue,Eyes],[Category2,Oranges,Green,Legs],[Category3,Pairs,Yellow,Arms],[,Mango,Gray,]];
  renderCategories(database,1);
}

function renderCategories(database, pos){
  mainPage = document.getElementById("mainPage");

  var catTitles = database[0];
  var catTitle = catTitles[pos];
  var allmainPage = database[2];
  mainPage.innerHTML = '<div class="input-field col s12 m12"><h3>'+catTitle+'</h3></div>';

  for(var i=0; i<allmainPage.length; i++){
    var categoryListValue = allmainPage[i][pos];
    if (categoryListValue !=""){
      mainPage.innerHTML += '<div class="row"><button onclick="nextStep(this,database)" value="'+categoryListValue+'">'+categoryListValue+'</button></div>';
    }
  }
}

function nextStep(selection, database){
  var selectedCat = selection.value;
  alert(selectedCat);
  var catTitles = database[0];
  alert(catTitles);
}
window.addEventListener("load", starting, false);

Answer №1

In order to pass the database, my recommendation is to utilize the JSON.stringify() function to convert it into a string and then use JSON.parse() to convert it back. Here's an example:

for(var i=0; i<allmainPage.length; i++){
    let categoryListValue = allmainPage[i][pos],
        databaseString = JSON.stringify(database);

    if (categoryListValue !="")
       mainPage.innerHTML += '<div class="row"><button onclick="nextStep(this,' + databaseString + ')" value="'+categoryListValue+'">'+categoryListValue+'</button></div>';
  }

Then, you can create a function like this:

function nextStep(databaseString) {
    let database = JSON.parse(databaseString)
}

While this approach may not be optimal, it should resolve your current issue.

If you'd like my advice, I recommend storing the database in local storage and accessing it using designated 'keys' for better organization (e.g., database01).

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 loop through an array and display a datalist in JSX?

In my React project, I am attempting to create a datalist using an array. Interestingly, when I pass the array and iterate through it, I can easily log the value of 'city' to the console. However, when I try to do the same iteration without JSX, ...

What is the best way to save the generated image in Aviary?

Here is the code snippet I'm working with: var featherEditor = new Aviary.Feather({ apiKey: 'your-client-id-here', theme: 'light', tools: 'all', appendTo: '', onSave: function(imageID, newURL) { var img = do ...

Having trouble retrieving Firebase data to display on a React chart

I am currently utilizing ApexChartJs in my React project. However, when attempting to retrieve dynamic data from my Firebase database, it returns undefined. https://i.stack.imgur.com/8lcnz.png Below is a snippet of code from my project: import React, { u ...

The variable "tankperson" is not recognized

While attempting to run an AJAX request upon page load, I encountered a particular error even though I have ensured that all the necessary libraries are included. The variable tankperson is derived from $_GET['name'] An unhandled ReferenceErr ...

What is the best way to extract the event time when a user clicks on an event in fullcalendar?

Is there a way to extract only the time from an eventclick event in fullcalendar? Currently, I am receiving details about the event including date and time. How can I specifically retrieve just the time (e.g. 6:00:00 am)? You can find the code snippet tha ...

What steps can be taken to verify that the submitted data is a legitimate numerical pair?

When I receive a string, it should be in the following format: number,number For example: 34.798,52.123 I need to verify that the number is indeed in this format before assigning it to variables and performing calculations. There is also a concern that ...

How to apply a series of spaces using span/tspan with jquery/javascript

Check out this fiddle: http://jsfiddle.net/jzLu4toe/3/ <span id='tghj'></span> $('#tghj').text('Hey There'); I'm facing an issue where I need to insert multiple spaces inside a span element. ...

Generate a customized form based on selected radio button option

Hey there! I'm curious to know if it's achievable to utilize Javascript/jQuery or Ajax in displaying a form depending on a radio button selection. Here's the scenario: I have two unique forms. If one radio button is chosen, I'd like to ...

Angular does not delay for promises to settle

Issue I am facing is related to Angular not waiting for promises to be resolved. The console inspection reveals that the provider and skills objects are not retrieved before the promises are returned. I have included the key parts of the code below. The s ...

How can we eliminate special characters from arrays stored in a PostgreSQL table?

I have a column named 'directedlink_href' in a database table that holds arrays starting with the '#' character. How can I remove the '#' character from all values within these arrays? For example... {#osgb4000000030451486, ...

Identifying Repetitions within an Associative Array

I am facing an issue with my foreach loop as it is inserting an array into the second level of my $bad_email array. This is what it looks like: ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98eef4f4fde1d8b6eaebeab6fbf7f5"&g ...

The window fails to retain the scroll position when overflow is enabled

Whenever I click on a specific div, I use jQuery to dynamically apply overflow: hidden to the html and body. $(".mydiv").on("click", function() { $("html, body").css("overflow", "hidden"); }); However, this action causes the window to scroll to the to ...

"Enhance your mobile user experience with swipeJS integration in jQuery

Trying to incorporate swipeJS into my jQuery Mobile application has been challenging. Below is the code snippet from the page where I attempted to implement swipeJS: FULL CODE: http://jsfiddle.net/unTHs/ (output on jsfiddle may vary) <div id="slider" ...

Proportional fluid image grid with responsive design

After implementing various media queries, I've managed to create an image grid using Bootstrap 4+ that looks great on specific devices and layouts. Here's the reference code: .cmd-three-img-container { position: relative; margi ...

Using the captured group as an array index in preg_replace with PHP

It appears that this task should be simple, but for some reason the code provided is not functioning correctly: $text = preg_replace('/test([0-9]+)/i', $array["$1"], $text); The intention of this code is to identify all occurrences such as &apo ...

What is the reason for the malfunction of this JavaScript code designed for a simple canvas operation?

I'm having trouble with the code below. It's supposed to display a black box on the screen, but for some reason it's not working properly. The page is titled Chatroom so at least that part seems to be correct... <html> <head> &l ...

Icons in Semantic-UI: Facing Difficulty in Accessing ("CORS Request Not HTTP"

Here's an example I'm working on: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Understanding - Main</title> <link rel="stylesheet" type="text/css" href="../semantic/dist/semanti ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

Having difficulty including a new key-value pair to a JSON object while using another JSON object

Looking to merge key value pairs from one JSON object into another. I've searched through various stackoverflow threads for solutions, but haven't found one that works for my specific scenario. const primaryObject = { name: "John Doe", ag ...

AngularJS: Move forward with controller execution after completion of a looped service method

Currently, I am implementing a networkService in Angular which is responsible for looping while the internet connection is unavailable. The goal is to resume execution once the connection is restored. Below is an example of a controller: MyApp.controller ...