How can we send a JSONArray through a dynamically generated button event and then retrieve the elements of the JSONArray?

In the following SCRIPT code snippet:

var jsonArr = [

  {
    " name": "John",
    "age": 31,
    "city": "New York"
  },

  {
    "name": "Smith",
    "age": 25,
    "city": "Dubai"
  }
];

function create()

{

  createButton(jsonArr);

}

function createButton(jsonArr)

{

  alert('inside function jsonarray length: ' + jsonArr.length);

  alert(jsonArr);

  var htmlcode = "input type=\"button\" id=\"subbtn\" value=\"Dynamic SUBMIT Button\" onclick=\"submitdata(this.id,'" + jsonArr + "');\"";

  document.getElementById("dynamic").innerHTML = htmlcode;

}

function submitdata(id, json_arr)

{

  alert('Button id is: ' + id);

  alert(json_arr);

  alert('inside submit data jsonarray length: ' + json_arr.length);

  // for (var i = 0; i < json_arr.length; i++)

  //{

  //                  var _el = json_arr[i];

  //                var name = _el.name;

  //              var age=_el.age;

  //            var city=_el.city;

  //  alert('Name: '+name);

  //}


}

Next, include a standard button with a value of "Click to Generate Button" and an onclick event of "create()".

The actual length of the JSON array is 2;

However, when passing this JSON array through the submitdata() event, the calculated length of the JSON array is 31 and the elements in the JSON array are undefined.

Could someone assist me in resolving this issue? I need to be able to access the elements of the JSON array inside submitdata().

Answer №1

Utilize the JSON.stringify() method by following this example

var jsonData = [

  {
    "name": "Alice",
    "age": "28",
    "city": "London"
  },

  {
    "name": "Bob",
    "age": "35",
    "city": "Paris"
  }
];

function generate()

{

  generateButton(jsonData);

}

function generateButton(jsonData)

{

  alert('inside the function jsonData array length: ' + jsonData.length);

  alert(jsonData);

  var htmlCode = "<input type='button' id='subbtn' value='Dynamic SUBMIT Button' onclick='submitInfo(this.id," + JSON.stringify(jsonData) + ");'\>";

  document.getElementById("dynamic").innerHTML = htmlCode;

}

function submitInfo(id, json_data)

{

  alert('Button id is: ' + id);

  alert(json_data);

  alert('inside submit data jsonData length: ' + json_data.length);

  for (var i = 0; i < json_data.length; i++)

  {

    var _el = json_data[i];

    var name = _el.name;

    var age = _el.age;

    var city = _el.city;

    alert('Name: ' + name);

  }
}
generate();
<div id="dynamic"></div>

Answer №2

To pass the jsonArray as a string and concatenate it to the on-click event, you can follow these steps.

"<input type='button' id='subbtn' value='Dynamic SUBMIT Button'   onclick=\'submitdata(this.id,"+arrString+")\'>";

var jsonArr = [

  {
    " name": "John",
    "age": 31,
    "city": "New York"
  },

  {
    "name": "Smith",
    "age": 25,
    "city": "Dubai"
  }
];

function create()
{

  createButton(jsonArr);

}

function createButton(jsonArr)
{

 var arrString = JSON.stringify(jsonArr);


 var htmlcode = "<input type='button' id='subbtn' value='Dynamic SUBMIT Button'   onclick=\'submitdata(this.id,"+arrString+")\'>";

  document.getElementById("dynamic").innerHTML = htmlcode;

}

function submitdata(id, json_arr)
{

  console.log(json_arr);

  console.log('inside submit data jsonarray length: ' + json_arr.length);

 
}
<div id="dynamic">
</div>
<input type="buttom" value="Click to Generate Button" onclick="create()">

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

Is the length of a complex match in Angular JS ng-if and ng-repeat greater than a specified value?

In my code, there is an ng-repeat that generates a table based on one loop, and within each row, another cell is populated based on a different loop: <tbody> <tr ng-repeat="r in roles | limitTo: 30"> <td>{{r.name}}</td> ...

Is there a method in JavaScript/jQuery to gently push or flick the scroll so that it can be easily interrupted by the user? Further details are provided below

I am looking for a solution in javascript that will allow the page to automatically scroll down slightly, but I also want the user to be able to interrupt this scroll. When using jquery for auto-scrolling, if the user begins manual scrolling while the ani ...

Deliver data in batches of ten when the endpoint is accessed

I am currently in the process of developing a web application using Next.JS and Node. As part of this project, I have created my own API with Node that is being requested by Next.JS. One particular endpoint within my API sends data to the front end as an ...

Receiving error message "[object Object]" while working with JavaScript

My current challenge involves adding an item to the shopping cart through a button click event that sends necessary data to a database table storing cart items. The issue arises with the item name, as I am encountering an error displaying [object Object] ...

Compiling Vue.js without the need for a build tool

Vue.js is the framework I've chosen for my PHP + JS application, and I'm using the full build of Vue by directly including it via a script tag without any build tool. I'm now wondering how I can pre-compile my templates without relying on b ...

AngularJS: Triggering events in one controller to update data in another controller

I've tried several examples, but I'm not getting the expected results. In my project, I have two controllers - one for a dropdown and one for a table. When a user selects an item from the dropdown, a factory triggers a get request to update the t ...

Platform error: Responses not specified for DIALOGFLOW_CONSOLE

I've been struggling with this issue for almost a day now and I'm at a loss for what else to try. For some reason, Dialogflow Fulfillment in Dialogflow ES is refusing to make any HTTP calls. Every time I attempt, I receive the same error message ...

Converting Node JS request to an API into React Fetch syntax

I have encountered a problem while developing an app in React-Native that connects with the Hubspot API. Initially, I tried to make the request using the Node JS request module, but it didn't work well with React Native when Expo was involved. Now, I ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

Ending a Firestore `get` query upon unmounting component

Currently, I am retrieving data from Firestore in the componentDidMount function. However, if I happen to change the component while it is still in the process of fetching data, an error occurs: Warning: Can't call setState (or forceUpdate) on an u ...

JavaScript function using recursion returning an undefined value

I have created a function that generates a random number and checks if it already exists in an array. If it does, the function generates a new number until a unique one is found and adds it to the array. However, I am encountering an issue where the functi ...

Issues with Google Fonts failing to load correctly

Would you mind taking a look at this issue for me? In all browsers except Firefox, the expected behavior is that a web font remains invisible until fully loaded, preserving space on the page. Interestingly, in Chrome and IE9 (the browsers I tested), ther ...

In which location can one find the compiled TypeScript files within an Angular 2 project?

As a newcomer to learning Angular 2, I've come across tutorials that mention all compiled files should go into the dist folder. These compiled files refer to typescript files transpiled into JavaScript. However, upon creating my project using Angular ...

Developing dynamic HTML content using Android and JavaScript to insert JavaScript code into the head tag dynamically

I need to incorporate a banner into my Android application in a specific way. Upon receiving the following Javascript code from the server: <script type="text/javascript" src="http://rm.face.ua/adriver.core.2.js"></script> <div id="adri ...

How to assign a click event to dynamically generated HTML elements using jQuery

My goal is to attach an onclick event to a dynamically inserted element using jQuery However, I am facing an issue where the function does not execute. I would appreciate it if someone could help me determine why this example is not functioning correctly ...

Building paths through a jQuery loop

Transform String into Delimited Array, Generate Loop of Check Boxes, and Build New String Given String = "Folder Tier1\Folder Tier2\Folder Tier3\Folder Tier4\Folder Tier5\Folder Tier6\" (Missing) Use "\" as a delimi ...

Updating the User Interface in ReactJS based on changes in the state

I am relatively new to ReactJS and I am currently working on building a Sudoku Solver. My goal is to update the state in real-time so that the user can visually see how the algorithm is progressing. However, my current code only updates the UI at the end ...

Injecting HTML into Vue component

Currently, I am passing some parameters into a Vue component <Slider :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']" :html="['<div>hello</div>', ' ...

Ways to retrieve the initial value and proceed with a subsequent subscription method

I have created a basic angular 7 web application with Firebase database integration. In my code, I am attempting to store the initial list in an array using the subscribe method and then display that array using console.log(). However, there seems to be a ...

What is the best way to transfer variables between two Vue files?

How can I transfer a variable between two Vue files? Hello, in my SendCode.vue file, I have a variable named NewEmail that I would like to use in another file called changePass.vue. Is there any way to do this? Can someone offer assistance? Thank you</p ...