Populating table with textbox value from previous HTML page

bboooooyintheuk :

I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.

This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?

I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).

Here's what I have so far:

HTML for textbox (page 1):

<div class="selecttier">
  <h1>5. Number of Clicks</h1>
  <input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>

JS on page 1:

$('#sales_order_form_button').click(function() {
        let table_info = [];
        $('input[type=checkbox]').each(
            function(index, value) {
            if($(this).is(':checked')) {
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                    }
                );
            }
        });
        let base64str=btoa(JSON.stringify(table_info));

        window.location = "page2.html?table_data=" + base64str;
        });

JS on page 2:

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i = 0; i < data_from_page_1.length; i++){
            let row = $("<tr></tr>");
            let recordName = $("<td></td>").text(data_from_page_1[i].name);
            let recordValue = $("<td></td>").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

        // code to sum CPC column
        var sum1 = 0;

        $("#output_table tr > td:nth-child(2)").each(
        (_,el) => sum1 += Number($(el).text()) || 0
        );

        $("#sum1").text(sum1);

        //datetime stamp
        var dt = new Date();
        document.getElementById("datetime").innerHTML = dt.toLocaleString();

Output HTML table (page 2):

<table id="output_table">
        <tr>
            <th>Name</th>
            <th>Value</th>
            <th>Number of Clicks</th>
        </tr>
        <tfoot>
            <tr>
                <th id="total" colspan="1">Total CPC:</th>
                <td id="sum1"></td>
            </tr>
    </tfoot>
    </table>

screenshot of HTML table on page 2

E. Zacarias :

As stated in the @Manu Varghese comment, the way to go would be using sessionStorage or localStorage.

First, let's differentiate both. According to the Stack Overflow question "HTML5 Local storage vs Session Storage", we have the following answer:

localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.

That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.

Considering they are used the same way and you must to choose between what better fits your case, I will proceed using sessionStorage.

For that, in the first page you must use:

sessionStorage.setItem("key", "value")

You may set the item right when you perceives a change, like in the input 'blur' event.

and when you land in the second page (right when jQuery calls its start event), you will retrieve your data using:

sessionStorage.getItem("key")

Take in mind that localStorage/sessionStorage can support a limited amount of data. Even if that limit is way bigger than URL, most browsers will store only 2.5MB to 10MB per origin, according to the browser implementation (you may test by yourself in the link recommended in MDN (Mozilla Development Network), http://dev-test.nemikor.com/web-storage/support-test/).

Also, you may want to avoid storing sensitive data in the storages, due to some some discussions about security, which seems not to be a complaint here.

Implementation in the given case

Your code can be modified in three steps:

  1. Change the way you save the data to use the storage
  2. Creates a JSON of an object containing the array, instead the make the JSON using the array itself. Then you can add more fields.
  3. Load the JSON object and its fields (the array and the number).

Step 1 - Changing to sessionStorage

Just now you have your Javascript on page 1 creating an array of data and stringifying that data to a JSON string.

If you want to use the storage rather than the URL for all the data, just change these lines of code from:

let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;

to the code that will save the data into a (local/session)Storage:

let jsonStr=JSON.stringify(table_info); // converts to JSON string
sessionStorage.setItem("oldData", jsonStr); // save to storage
window.location = "page2.html"; // navigate to other page

Notice that the storage can receive any string, but only strings, then we can remove the btoa function, but we must keep the stringify.

Step 2 -- Adding more data to save

Now you have one JSON that is an array of items. But what do you want is to include one more field, parallel to this array. Of course, you can't include it in the array, as it is a different thing. So, what we must to do is to create a JSON object which has a number field AND the array field itself.

Your function to create the array is all ok, then we will use the same "table_data" as the array and include it to a new JSON object:

let table_data = []; // the array you have
$('input[type=checkbox]').each(
    ... rest of code ...
); // the function that creates the array (I abbreviated it here)

// Creates an object with an array and a number
let jsonObj = {
    table_data: table_data,
    number_of_clicks: theNumberYouHave/* your variable with the number here */
};

// This is the bit above with CHANGES into variable names
// Instead of "table_data", now we save "jsonObj"
let jsonStr=JSON.stringify(jsonObj); // converts the "jsonObj" to a JSON string
sessionStorage.setItem("oldData", jsonStr);
window.location = "page2.html";

Remember to change "theNumberYouHave" to whatever your variable with the number is called. The you will append the number as a field of the JSON object.

In other words, this simply will create an structure like that:

{
  number_of_clicks: 5216,
  table_data: [
    { name: "...", value: "..."},
    { name: "...", value: "..."},
    { name: "...", value: "..."},
    ...
  ]
}

See? Your table_data is still there, but with a new sibling (number_of_clicks) inside an object.

Step 3 -- Loading data from page 1

For now, you have these two lines of code in page 2 to read data from page 1:

let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));

What do you need there, is to simply replace the getUrlParameter function to read from the storage, and remove the atob function to reflect the changes we made in page 1, this way:

let jsonObj = sessionStorage.getItem("oldData"); // reads the string
let data_from_page_1 = JSON.parse(jsonObj); // parse the JSON string
let table_data = data_from_page_1.table_data; // grab the table data
let number_of_clicks = data_from_page_1.number_of_clicks; // grab the number

Now you are free to use the variable "table_data" like you did, and to use the "number_of_clicks" in the way you want to use it. It is the number passed from page 1, then you may set it to your table cell.

You have it with the unique ID "sum1", the you may just:

$("#sum1").text(number_of_clicks);

And you are done!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11993&siteId=1