Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi I am a beginner web developer and am trying to build the interface of a simpl

ID: 646198 • Letter: H

Question

Hi I am a beginner web developer and am trying to build the interface of a simple e-commerce site as a personal project.The site has multiple pages with checkboxes. When someone checks an element, it retrieves the price of the element and stores it in a variable. But when I go to the next page and click on new checkboxes products the variable automaticly resets to its original state.How can I save the value of that variable in Javascript?

This is the code I've writen using sessionStorage but it still dosen't work when I move to next page the value is reseted.

How can I write this code so that it dosen't reset on each page change. All pages on my website use the same script.

$(document).ready(function () {
    var total = 0;

    $('input.check').click(function () {
        if ($(this).attr('checked')) {
            var check = parseInt($(this).parent().children('span').text().substr(1, 3));
            total += check;
            sessionStorage.var_name = 0 + total;
            alert(sessionStorage.var_name);

        } else {
            var uncheck = parseInt($(this).parent().children('span').text().substr(1, 3));
            total -= uncheck;
        }
    })
})

Explanation / Answer

You have three basic options.

Send the data to the server and save it with the user's HTTP session. Then when you load a page that needs the data, you just pull it out and use it. This probably is not ideal for your case, but is still necessary for certain things. This is also the safest solution as it is unlikely a user can turn off any functionality in there browser to prevent it. If a full page load is too much, you can send that data with a asynchronous request (Ajax), but this does require that JavaScript is enabled. Although I don't think that is much of a problem anymore for general websites.

Save the data in a cookie. Cookies are sent back and forth with each HTTP request and response. There's a limit to how big your cookies can be, so if you are sending a lot of data, you might not want to do this. If you do, you'll want to make sure you delete the cookies when you're done with them so they don't bloat your requests and responses.

Take advantage of the client side data storage APIs in the various browsers. I am not up to speed on of this has been standardized and/or fully implemented by all major browsers yet, but the last time I checked there were libraries that abstracted away the various details. I know jQuery does this, but I'm sure there are others.