Using jQuery to pass dynamic values to a plugin function

I'm currently utilizing the JSONTable plugin and attempting to dynamically pass values to the 'head' and 'json' parameters by extracting them from an array object. For instance, I aim to load a new json file, convert it to a JavaScript object, and extract the updated 'head' and 'json' attributes.

$("#dataTable").jsonTable({
    head : ['#','Operating System','Market Share'],
    json : ['id', 'name', 'share']
});

I've encountered similar issues while working with other plugins. Even though this might seem straightforward, I have yet to discover how to achieve this. One approach I tried was passing the entire function as a string, but that only converted it into a string rather than a function object. Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

If you want to display the properties of the initial element in the array as column headers, you can refer to them as such (here is a test):

HTML:

<textarea id="data" cols="50" rows="8">[
{"id": 1, "name": "Apple", "price": 1200},
{"id": 2, "name": "Samsung", "price": 1000},
{"id": 3, "name": "Google", "price": 800}
]</textarea><br />
<input type="button" id="generateButton" value="Generate Table" /><br/>
<table id="itemTable"></table>

JavaScript:

function generateTable(tableId, jsonData) {
    var data = JSON.parse(jsonData),
        columns = [];

    if (!(data instanceof Array) || data.length === 0)
        return;

    for (var key in data[0]) {
        if (data[0].hasOwnProperty(key))
            columns.push(key);
    }

    $("#" + tableId)
        .html("<table id='" + tableId + "'><thead></thead><tbody></tbody></table>")
        .jsonTable({
            head: columns,
            json: columns,
        })
        .jsonTableUpdate({
            source: data
        });
}

$("#generateButton").click(function () {
    generateTable("itemTable", $("#data").val());
});

Output:

id   name      price
1    Apple     1200
2    Samsung   1000
3    Google    800

Feel free to modify the values in the <textarea> and click the button to see the changes reflected in the table. Remember to update column names throughout the JSON document if you decide to change them.

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 proper way to utilize the value of a Node.js promise in a different function?

In my Node.js application, I have two functions defined. The first function is structured like this: function checkAdd ( address /* : string | void */ ) /* :Promise<Object[]> */ { var convertToLowerCase = address.toLowerCase() return Promi ...

The Ajax GIF Loader is not functioning in the latest versions of Internet Explorer and Firefox, but it is running smoothly in

The animated GIF loader functions correctly in the latest version of Chrome, but does not animate when viewed in IE and Firefox. Below is the code snippet: $("#DIALOG").dialog({ buttons : { "Yes" : function() { ...

Step-by-step guide on building an admin dashboard for your React application

Recently, I built an online store website using React. Currently, the data is being loaded from a local .json file. However, I am in need of creating an admin panel to allow the site administrator to manage and update cards and data on their own. Is there ...

Building a single-page app optimized for mobile viewing with Foundation framework

Currently facing an issue with the scaling of the viewport on certain mobile devices when loading new content via ng-include in our responsive website built on Foundation. The problem arises as the width of the page breaks, leading to horizontal scrolling. ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...

Incorporating the Revolution Slider jQuery plugin within a Vue.js environment

Currently, my goal is to transform an html project into a vue application. The initial project utilizes a jquery plugin for Revolution slider by including them through script tags in the body of the html file and then initializing them: <script type= ...

Ignoring empty lists in Jackson - A simple guide

My web service needs to pass these entities as JSON objects: @Entity(name = "exams") public class Exam { @Id @GeneratedValue private int id; @Column(name = "exam_name") private String name; @JoinColumn(name = "exam_id") @One ...

"Exploring the world of Vue.js and videojs: refreshing the video

Is there a way to refresh the videojs in Vue (3)? Here is the code snippet I am currently using: <template> <video-js controls="true" preload="auto" ref="video_player" class="video-js vjs-big-play-centered&quo ...

Setting Start and End Dates in Bootstrap Vue Datepicker to Ensure End Date is After Start Date

My Vue.js form includes two BootstrapVue datepickers for holiday management. Users can define the start date and end date of their holiday, with the condition that the end date must be equal to or greater than the start date. Here is my current implementat ...

What is the best way to create a scrollable tbody in an HTML table using React?

In my current project, I am using React, Node, Express, and Postgres to fetch data from a database. The issue I'm facing involves creating a scrollable table within a div that spans the entire screen width. Initially, I had to apply display: block to ...

Utilize JavaScript and jQuery to extract the selected text's context from a webpage

I'm looking to extract the contextual information surrounding a selected text on a web page, specifically the 25 words before and after it. I've tried using JavaScript and jQuery with the following code snippet but unfortunately, it doesn't ...

Angular, JavaScript, and PHP are three powerful programming languages that

This file contains HTML code <ul class="list"> <li id="numword" data-score="{{item.score}}" class="" ng-repeat="item in words track by $index"> {{item.word}} {{item.score}} </li> </ul> Here is the visual representa ...

JavaScript combined with a dynamic menu, a customized current link style using CSS, and a site built on PHP

Here's my current website setup: My website is modular and uses dynamic inclusion. The header is a crucial part of the main page, which is responsible for displaying content from specific links on the site. External links to CSS and js files are incl ...

Getting callback data from a function in the AWS SDK without using asynchronous methods

I have a code snippet that fetches data from AWS using a function: main.js const { GetInstancesByName } = require("./functions"); var operationmode = "getinstances"; if (operationmode == "getinstances") { let getresult = ...

Execute GTmetrix report retrieval using React Native

Attempting to access GTmetrix report using react native. I am struggling with react native development, any assistance would be greatly appreciated. Code: constructor(props){ super(props); this.state={ isLoading:true, dataSource:nu ...

angularjs dynamically display expression based on controller value

I'm not the best at explaining things, so I hope you all can understand my needs and provide some assistance here. Below is a view using ng-repeat: <div ng-repeat="item in allitems"> {{displaydata}} </div> In my controller, I have the f ...

The Ajax request is successfully looping through multiple files, however, it is not properly sending them to the server. As a result, only one file

I have been working on an ajax request that successfully retrieves information about files, such as the number of files, their names, and looping through them. Now, I am faced with the challenge of saving these files to a local folder on my computer. I hav ...

Deselect the checkbox that was initially selected when an alternative checkbox option has been chosen

I am trying to implement a feature where there are 2 groups of checkbox options on the same page. Below is the code snippet: <div class="col-xs-12"> <label class="checkbox-inline"> <input type="checkbox" th:field="*{borrowerRace1}" th:val ...

Custom cellRenderer prevents Ag Grid's autoHeight and wrapText features from functioning properly

I've been attempting to adjust the formatting of a long cell value by wrapping the text. According to the documentation, setting autoHeight=true and wrapText=true works fine without any cellRenderer components. However, when using a cellRendererFramew ...

managing arrays in JavaScript with multiple tables

**I have successfully written code for calculating the sum of inputs in one table** $('#example122').on('input', '.calculate', function () { calculateTotal(); }); function calculateTotal() { var grandTotal = 0; $ ...