Setting a JavaScript Date object in data- attributes: A tutorial

Utilizing google chart for plotting a graph in my Rails application.

The data used for the chart is dynamically generated within a model.

Company#my_chart_data

def my_chart_data
  [
        ['date', 'value1', 'value2'],
        [Date.new(2017,1,11), 1, 2],
        [Date.new(2017,1,13), 3, 5],
        [Date.new(2017,1,16), 0, 7]
    ]
end

In the view, the method is invoked to fetch the chart data.

<%= content_tag :div, "", id: "my-chart-data",
                data: {rows: company.my_chart_data} %>

Subsequently, the chart is generated using JavaScript. An important step involves converting date strings into Date objects due to Ruby's conversion of Date instances into strings.

function drawMarginBalance(type) {
    var array = $('#my-chart-data').data('rows');

    // convert date string to date object
    array = array.map(function (obj) {
        if (obj[0].match(/\d{4}-\d{2}-\d{2}/)) {
            return [new Date(obj[0])].concat(obj.slice(1, 3));
        } else {
            return obj;
        }
    });

    var data = google.visualization.arrayToDataTable(array);
    var options = {
        seriesType: 'bars',
        series: {1: {type: 'line'}}
    };
    new google.visualization.ComboChart(document.getElementById('my-chart')).draw(data, options);
}

The code performs as expected. However, I aim to input a Date object instead of a String within the data- attributes.

Seeking guidance on how to accomplish this task efficiently.

Answer №1

As mentioned by @Darkrum, it is not possible to store anything other than a string in a data- attribute or localStorage. It is important to choose a consistent format, such as using either a time stamp or the full UTC String. When you need to retrieve the value later on, simply pass the string or timestamp to a new Date( ) object and manipulate the resulting object accordingly.

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 change the content of a table cell by clicking on a link?

I am dealing with a table that has data in three columns. The first two columns contain just one or two words each, but the third column contains around 1000 characters. I want to be able to toggle the visibility of this third column's data when click ...

Error: The function 'readAsDataURL' of 'FileReader' was unable to be executed as parameter 1 is not a 'Blob' type

My issue involves a javascript Filereader that is giving me an error Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. It's a hit or miss situation. Sometimes it wor ...

"Creating a new element caused the inline-block display to malfunction

Can someone explain why the createElement function is not maintaining inline-block whitespace between elements? Example problem First rectangle shows normal html string concatenation: var htmlString = '<div class='inline-block'...>&l ...

Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented: function toggleHiddenContent(tabClass) { let t = document.querySelectorAll(tabClass); for(var i = 0; i<t.length; i++) { t[i].classList.toggle="visible-class"; } } .hidden-conten ...

Once I have verified the accuracy of certain $_POST variables, I am looking to close my window. Is there a way to achieve this using JQuery?

<?php if($_POST["some_variable"]){ echo "this window should be closing now"; } ?> How do I implement a JQuery function to close the window? The code snippet below demonstrates how the window was initially opened... $('.new_windo ...

The HTML canvas may sometimes produce inaccuracies in the bytes returned by the getImageData function, a phenomenon known as "

I've come across an issue where the getImageData function of an HTML canvas is returning incorrect byte values. To illustrate, I created a 1x1 pixel image using the following Python code: from PIL import Image import numpy as np a = np.array([[[12, ...

Modifying HTML elements using jsdom

When testing an angular controller within a large module, I encountered the "Controller is not a function" error. To fix this issue, I realized that I need to mock the DOM and set: <html> to <html ng-app='myApp'> by manipulating ...

how can I determine the selection status of a checkbox using the "this" keyword as an id selector in JavaScript?

function checkSelected() { if ($(this).prop("checked") === false) { alert("was unselected"); counter++; $(this).prop("checked", true); } if ($(this).prop("checked") === true) { ...

Vessel + AngularJS - CORS rejection in action

Snippet: @route('/characteristicsToBestWeb', method='OPTIONS') def respondToCharToBestQueryWebOptions(): response.headers['Access-Control-Allow-Origin'] = settings.allowed_web_origin response.headers['Access-Cont ...

calculate the product of the table's td element

Recently, I encountered a task where I had to make a table with an editable quantity cell. Whenever the quantity was changed, it needed to be multiplied by the value in another parent td. Here is the code snippet that helped me achieve this: $(document) ...

mass editing - undesired demands or data bombardment

Lately, I've been extremely frustrated with an issue I've encountered over the past 4 days. When attempting to update multiple items within my store simultaneously, I'm experiencing a strange payload behavior. To elaborate on what I mean by ...

Issues with Material UI React's test cases failing in JEST and ENZYME testing frameworks

I am facing an issue with my connected component that has MaterialUI integrated into it. Despite my efforts, the tests keep failing and I haven't been able to find any helpful resources online to troubleshoot this problem. I would greatly appreciate ...

Identify the difference between a regular function and a constructor in JavaScript

How can we determine whether a function in javascript is a simple, plain (anonymous) function, or a constructor (a function with a prototype)? I have developed the following function for this purpose: function checkFunctionType(value) { var ownPropert ...

Transmitting Chosen Information from One Webpage to Another in HTML

I have a form that passes data from one page to another when the apply button is clicked. The goal is to display the corresponding career title (such as Java Developer) on the next page. I attempted to accomplish this using JavaScript. career.html: <f ...

Is there a way to retrieve the current map center coordinates using the getCenter function in @react-google-maps/api?

I am currently working with the GoogleMap component provided by @react-google-maps/api, but I am struggling to figure out how to obtain the latitude and longitude coordinates of the map's center after it has been moved. After some research, I came ac ...

iPad is playing the incorrect file when using .play(). Any ideas on how to fix this issue?

Currently, I am developing a web application that involves a div element with dynamic text content that changes based on user interactions. To enhance the user experience, I decided to incorporate audio elements by creating an array containing correspondin ...

What causes the issue of the 'MERGE' statement in Node.js resulting in the creation of duplicate nodes in Neo4j?

Currently tackling a Node.js project involving the creation of nodes in Neo4j using the 'MERGE' statement. Despite employing 'MERGE' to prevent duplicate nodes, duplicates are still being generated at times. Extensive searches through ...

Guidelines for integrating deep links into a ReactJS Ionic Android application

I have recently converted my ReactJS project into an android project following a tutorial. Now, I have successfully created an APK file and would like to configure the app to open when a specific URL is clicked on a mobile browser. Any guidance on how to a ...

Encountering a problem with AngularJS - receiving the [ng:areq] error, for more information visit http://errors.angularjs.org/1.3.2/ng/areq

While working on my CRUD angularApp, I encountered a strange error in Chrome dev tools. Here is the complete error message: error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=DbController&p1=not%20a%20function%2C%20got%20string at angular.j ...

Is there an easy way to determine if an object exists in a scene using THREE.js?

Is it possible to dynamically add and remove objects from a scene with just a click? Currently, I am using scene.add(object) and scene.remove(object) for this purpose. I am wondering if there is any method to verify whether the object is already in the s ...