Utilize Bootstrap DataTable Sparkline to extract information from a comma-delimited string rather than an array

I have successfully implemented a Bootstrap DataTable component in my Asp.net Core MVC App to display data from my database. However, I am facing a challenge when trying to add a sparkline to a column. The sparkline component requires an array of values, but I only have a comma-separated string. I need assistance in understanding how to modify the JavaScript code to accommodate my data type.

To simplify the issue, I created a new App without a database and directly defined data in the JavaScript, similar to the example shown here: https://datatables.net/examples/basic_init/stocks.html

While this example works perfectly, I need to adjust the format of values in the "last" field from an array to a string, as shown below:

  var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": "2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59"
        },
.....
]

Here is the JavaScript code that requires modification:

$(document).ready(function () {
    debugger;
    var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": [2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59]
        },
        {
            "name": "Spry Media Productions",
            "symbol": "SPMP",
            "last": [1.12, 1.11, 1.08, 1.08, 1.09, 1.11, 1.08]
        },
        ...
    ];
    
    // DataTable initialization and other functionalities
    
});

Despite trying to use .split(", ") in the data rendering section, I have been unsuccessful. Debugging the JavaScript code (in site.js) has also proven challenging, as console.log statements do not produce any output.

UPDATE

Thanks to @andrewJames, my code now works flawlessly without the need for any data transformation. I have also added additional functionalities such as grouping by columns and formatting datetime display using moment.js.

Here is the updated code:

$(document).ready(function () {
    // DataTable configuration with grouping and datetime formatting
    
});

One remaining issue is that when I enable responsive: true, the sparkline column gets hidden. Upon expanding the row to show hidden columns, the entire array of values is displayed instead of the sparkline. It seems that the drawCallback function is not applied to hidden columns.

I believe I need to capture the mouse click on the expand icon and dynamically inject the canvas to display the sparkline, but I am unsure how to achieve this.

Answer №1

If you have strings with comma-separated numbers and want to convert them back to arrays of numbers, you can use the following code snippet:

for(i = 0; i < data.length; i++) {
    data[i].last = data[i].last.split(",").map(element => {
        return Number(element);
    });
}

This code snippet first splits the string using the comma as a delimiter and then maps over the resulting array to convert each string to a number.

Where should you place this code?

In your code snippet provided, this code should be placed after the line:

data = stock_data;

For a complete demonstration, here is a self-contained demo:


Update

In response to a comment about using the following as the data source...

ajax: "api/ApartmentsAvailables"

You can adapt the logic mentioned above by expanding the DataTables ajax option with the dataSrc option. This allows you to preprocess the JSON received from the Ajax URL and convert the comma-separated strings back to arrays of numbers using similar logic as demonstrated.

"ajax": {
    "url": "api/ApartmentsAvailables",
    "dataSrc": function ( json ) { // JSON with strings

      // Transform the JSON here...
  
      return json;  // Updated JSON with arrays
    }
}

If needed, you can use console.log( json ) to verify the JSON structure before and after transformation. Adjust the code to fit your actual JSON structure, and refer to DataTables documentation for more information on dataSrc usage.

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

Performing a fetch() POST request in Express.js results in an empty body object being generated

Purpose: Implement a function in fetch() to send specified string data from the HTML document, for example "MY DATA" Here is the code snippet: HTML Code: <!DOCTYPE html> <html> <body> <script type="text/javascript"> function ...

Updating an Angular directive with dynamically added ng-module and ng-change attributes

Can someone check if I'm on the right track? Preamble: I've created a Typeahead class that fetches data and keeps it within itself. The class has the following structure: input: stores the search text. list: stores the results. change: a funct ...

Angular does not allow the transfer of property values from one to another

As of late, I have delved into learning Angular but encountered an issue today. I have the following Component: import { Component, OnInit } from '@angular/core'; import { SharedService } from '../home/shared.service'; import { IData } ...

Challenge encountered when attempting to detect multiple submit buttons using jQuery

I am currently attempting to identify which of the four submit buttons was clicked using jQuery 1.7.2. When any one of three specific buttons is clicked, I want an alert box to appear displaying the value of that particular button. Below is the HTML code s ...

Repetitive series of HTTP requests within a looping structure

Within my AngularJS project, I encounter the need to execute a varying number of HTTP requests in sequence. To achieve this, I believe that utilizing a loop is necessary: for (let i = 0; i < $scope.entities.length; i++) { MyService.createFixedValue ...

Tips for getting Vue's element-ui validateField() function to function correctly in conjunction with v-if?

Kindly observe the password fields. The fields for 'Password' and 'Confirm Password' are displayed upon clicking on the 'Change Password?' button. The provided code functions properly and effectively validates the form using ...

The action of setting the inner HTML of "main" to "testing" is temporary and will revert back to its original state rather than permanently change

In this snippet of my Java.html code, I am inserting the <a href='' onclick='load_des()'><li><p>$row[Title]</p></li></a> element into the div element with the ID "main". This content is being echoed f ...

The Next.js error message reads: 'Issue with setting properties on undefined entity (specifically 'hook')'

This issue seems to occur either when the app is launched or when updating the Redux state. It may not show up consistently for every state update, but for some reason it persists throughout the entire app. What I have attempted so far: Removing node mod ...

karma is failing to run the test scenario

I am just starting out with karma and I'm having trouble running test cases. Below is my setup: karma.config.js module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) base ...

jQuery Form Validator: requiring double submission

I've been working on implementing the Form Validator using Jquery. After some testing, I noticed that I have to click the submit button twice before the validation kicks in. Why is that? The script is housed in a separate file and included in my proj ...

Tips for updating text in a freshly opened window using JQuery or JavaScript

I have a function that is triggered by a button click to open a new window or tab, display an alert, and update text. Here is the code snippet: function nWin(p) { var setStyle = "<style rel='stylesheet'>\ .vTop {\ ...

Preserve jQuery-enhanced webpage changes permanently

I am looking to permanently save modifications made on an HTML page using JQuery. I have come across suggestions about achieving this by sending an Ajax call and storing the data in a database table. However, I am unsure about what exactly needs to be save ...

How to display percentage value on ReactJS Material UI progress bar

For displaying the progress completed in numbers, I utilize the Linear Determinate component. Take a look at the image below to see how it appears. ...

Can you explain the functioning of knockout container less syntax? (does it have any drawbacks?)

There are numerous instances and examples of using knockout ContainerLess syntax, although I find it challenging to locate proper documentation from their site. Initially, my question was "is it evil?" but upon realizing my lack of understanding on how it ...

ASP.NET Core does not support jQuery.validate functionality

After successfully creating a functional jQuery.validation form using HTML, CSS, and JS with dependencies like jQuery and Validation, I encountered an issue when implementing the same code in a clean ASP.NET Core web project. It seems that my custom valida ...

Substitute placeholders in the HTML code with Angular syntax

Lately, I have been encountering some issues with AngularJS. I have defined multiple scopes like this: app.controller('mainController', function($scope) { $scope.siteURL = "my website url"; }); When using the {{siteURL}} variable in ...

Ways to dynamically generate a card using NuxtJS

I'm just starting out with NuxtJS and I'm curious about how to generate a v-card within a v-dialog box. Imagine this scenario: I have an "add" button that triggers a v-dialog, where I can input information into a form. After submitting the form, ...

When the form is submitted, the values of the items are being reverted back

I'm currently working on a single web page using nodejs, expressjs, and mongoDB. On the page, I have two text boxes that define the filter clause for the collection in mongoDB. Additionally, there is an HTML table that displays the documents from the ...

A regular expression in Javascript that can be used to identify at least one word starting with a number among multiple words, with a

Currently, I am utilizing JavaScript Regex to validate an input field based on specific conditions: The value must consist of only alphabets and numbers There should be a minimum of two words (more than two are allowed) Only one word can start with a num ...

What is the reason for the JavaScript TypeError (undefined) being triggered when this object is used within a function?

I have defined a new object like this: function node(){ this.tag = null; this.Tdata = []; this.Tchilds = []; } Now, I am trying to use this object in a function: function Validate(root /*Ass ...