Storing and retrieving an HTML editable array using COOKIES in JavaScript

In my code, I have created an editable array where you can input student information. A button computes the grade for each student at the end of the line. Additionally, there are buttons to add rows for students and columns for different assignments.

Now, I want to enhance the functionality by adding two more buttons - one to save the filled array in a Cookie and another to load this information back into the array.

I'm currently facing a challenge when it comes to saving and loading data using cookies.

Below is the snippet of my code:

var ass = 1;

// Functions for calculating grades, adding rows and columns

...

// Buttons linking and functions for saving and loading cookies.

...

function save_cookie() {
    setCookie("array", array, 30);
    
var array = document.getElementById("Student_Table");

alert (array + " saved");
}

function load_cookie(){ }
...
<table class="tg" id="Student_Table">
  <tr>
    <th class="tg-baqh">Student Name<br></th>
    <th class="tg-baqh">Student ID<br></th>
    <th class="tg-baqh">Assignment 1<br></th>
    <th class="tg-baqh">Final Grade<br></th>
  </tr>
  <tr>
    <td class="tg-yw4l" contenteditable="true"></td>
    <td class="tg-yw4l" contenteditable="true"></td>
    <td class="tg-lqy6" contenteditable="true"></td>
    <td></td>
  </tr>
</table>

<a href="#" class="myButton" id="click" onclick="Grade()">grade</a>

<a href="#" class="myButton" id="click2" onclick="add_row()">add row</a>

<a href="#" class="myButton" id="click3" onclick="add_column()">add column</a>

<a href="#" class="myButton" id="click4" onclick="save_cookie()">Save data</a>

<a href="#" class="myButton" id="click5" onclick="load_cookie()">Load data</a>

Your assistance is greatly appreciated.

Regards,

Eric

Answer №1

When briefly looking over the code, a few changes come to mind:

function save_cookie() {
    setCookie("array", array, 30);

    var array = document.getElementById("Student_Table");

    alert (array + " saved");

}

Perhaps it would be better structured like this:

function save_cookie() {

    var array = document.getElementById("Student_Table");

    setCookie("array", array, 30);

    alert (array + " saved");

}

Additionally, it's recommended to encode the data or convert it into JSON format:

function save_cookie() {

    var array = document.getElementById("Student_Table");

    var json = {
           "array": array
    }

    setCookie("array", JSON.stringify(json), 30);

    alert (array + " saved");

}

In the getCookie function, consider implementing the following:

if (c.indexOf(name) == 0) {
    var cstring = c.substring(name.length, c.length);

    // error handling omitted
    return (JSON.parse(cstring)).array;
}

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 it possible to add some color to the first table in the div

Is it possible to change the background color of the first table within this Div tag that contains three tables? <div id="WebPartWPQ2" width="100%" HasPers="false" allowExport="false"> <table width="100%" border="0" cellSpacing="0" cellPadding= ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

What is the reasoning behind the "open in a new tab" function triggering a GET request?

Check out this HTML tag: <a href="#" id="navBar_navBarInput_3_subNavDropdownInput_0_subNavLinkInput_0" onclick="redirectPost(4,'EntryData.aspx');">My Cool Link</a> The Javascript function "redirectPost" function redirectPost(id, ur ...

Updating the input value in a React application

With a list and an edit button, upon clicking the edit button, a new modal opens. How can I auto-populate the selected username email? The server-side response is {this.test.name}, where I provide him with the input value to auto-populate. However, when ...

Tips for displaying two dynamic variables that are interdependent

For instance: Controller: AllBooks[{ book1:{ hardcover{price:25.99},e-book{price:1.99} } }, book2:{ hardcover{price:60.00},e-book{price:2.99} }]; $scope.bookchoice = function(selectedBook) { $rootScope.choice = selectedBook;} $scope.booktype = functio ...

Dynamic Translation Service for Ionic 2 and Angular 2 with ngx-translate

Currently working on an Ionic 2 app and looking to implement object translation directly from the server response instead of using a JSON file. Utilizing ngx-translate Here's an example of the object received: { "name": ["Hello", "Hola", "Bon Jour" ...

What is the best way to conceal a row when a particular field is devoid of content?

Is it possible to hide an entire table row if a field is empty? For example: https://i.sstatic.net/tMW7L.png If a certain field is empty, I want the entire row to be hidden, either using JavaScript or jQuery. I have tried some methods but none of them fu ...

Shuffle contents of a Div randomly

I'm currently in the process of developing a new website and I need to randomly move the news feed. To achieve this, I have created an array containing the list of news items. The array is then shuffled and placed within the news feed section. Althou ...

How can I retrieve data from a JSON object?

I am currently in the process of utilizing the Bing Isochrone Api. I have established my HTTP request in Angular using the HTTPClient. Below is an example of the dataset I receive back: { "authenticationResultCode": "ValidCredentials", "brandLogoUri": "ht ...

Difficulty encountered in utilizing clearTimeout for undefined popover variable

I have implemented some coffeescript in users.js.coffee which successfully triggers a Twitter Bootstrap popover when hovering over a username. However, I am now looking to add a timeout functionality to automatically hide the popover if a user doesn't ...

Leveraging the callback function to display information from a JSON file

Attempting to retrieve JSON data from a PHP file and display it. Managed to successfully request the data via AJAX and log it to the console. (At least one part is working). Tried implementing a callback to ensure that the script waits for the data befor ...

Game board in disarray due to an unexpected array exceeding its limits

In the code for a slightly more complex version of tic tac toe, there is a method that is causing an issue. Whenever the computer attempts to make a move, it triggers an array out of bounds -1 error. This is particularly perplexing because I have taken c ...

The argument represented by 'T' does not align with the parameter represented by 'number' and therefore cannot be assigned

I am confused as to why, in my situation, <T> is considered a number but cannot be assigned to a parameter of type number. Changing the type of n to either number or any resolves the issue. Error: https://i.sstatic.net/h1GE9.png Code: const dropF ...

Is it advisable to load 10,000 rows into memory within my Angular application?

Currently, I am in the process of creating a customer management tool using Angular.js that will allow me to directly load 10,000 customers into the $scope. This enables me to efficiently search for specific data and manipulate it without the need for serv ...

Creating an AI adversary for a simple Tic Tac Toe game board: a step-by-step guide

Being new to programming, I recently completed a basic Tic Tac Toe gameboard successfully. However, as I progress to the next phase of my assignment which involves implementing an AI opponent, I encountered several challenges. As a novice in programming, ...

Improprove the Express Router in a Node.js application

Is there a way to avoid repeating the isUserAuth and isAdminAuth middleware on each endpoint? Can I apply them just once so they work for all routes without having to specify them individually? const { createBranch, getAllBranch, getBranch } = require(&apo ...

Incorporate a Vue.js computed property into the data retrieved from a server

Coming from Knockout.js, where observables are easily created by defining them, I'm curious if there's a similar approach in Vue.js. let vm = { someOtherVar: ko.observable(7), entries: ko.observableArray() }; function addServerDataToEnt ...

Identifying and capturing changes in child scope events or properties in Angular

I am encountering an issue with my form directive where I need to intercept ng-click events nested within varying child scopes of the form element. However, I am struggling to hook into these events or child scope properties in a generic way. For demonstr ...

Steps to retrieve the final page number from ngx-pagination with Angular

Is there a way to utilize Custom templates within ngx-pagination in order to ensure that the first and last buttons function properly when clicked? Currently, I have utilized pagination-template to accomplish this... How can I dynamically determine the la ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...