-1

I want an easy way to set a variable value equal to n when function(n) runs.

<a href="products.html" onclick="loadProdType(0)">Hovedkort</a>
<a href="products.html" onclick="loadProdType(1)">Prosessor</a>
<a href="products.html" onclick="loadProdType(2)">Arbeidsminne</a>

I have this piece of HTML code. And I want the loadProdType function to change the value of a variable prodCat according to loadProdType's value. I tried the code under with and witout localstorage.setItem(loadCat, j). The js document is linked and there are no linking errors cause other pieces of code runs as it should.

var loadCat = 0 
function loadProdType(j){
loadCat = j}

How can I set loadCat's value equal to loadProdType's value/parameter.

Thanks in Advance.

Edit:

Unsure how to set local storage for this but what I want the code to do is the following:

  1. Change the value of variable prodCat according to the value of the onclick function.
  2. Redirect to: products.html
  3. When in products.html I run a piece of code that uses the prodCat value to choose a spesific index in an array.

All in all I just need to be able to change prodCat on one page(to the value of a funcion or with a onclick) and have it saved on the next.

Last edit I'll create different functions for each onclick and try that with local storage.

  • why is your loadCat variable declared outside the function ? – Jyotirmoy May 15 '22 at 10:23
  • 1
    @Jyotirmoy Because it's not visible outside the function otherwise? –  May 15 '22 at 10:32
  • So the idea is to 1. store the index in localStorage 2. navigate to products.html 3. load the index value 4. display the correct product accordingly? Can you edit your question to show the actual localStorage code you've tried? –  May 15 '22 at 10:36
  • 1
  • 1
    This will update the variable. Most likely the problem is that you aren't doing anything to look at the updated value of it. You need to provide a [mcve]. (Humm, since you are navigating to a new page, perhaps you are expecting `var loadCat = 0` to *not* set that variable to `0` when the new page loads?) – Quentin May 15 '22 at 11:14
  • 1
    https://stackoverflow.com/questions/27765666/passing-variable-through-javascript-from-one-html-page-to-another-page is probably a duplicate. – Quentin May 15 '22 at 11:16
  • @Quentin. Yes, I want that it keep the given value from the previous page. – Ravn Nordling Tønnesen May 15 '22 at 11:19

1 Answers1

2

You need either ? in the URL or local storage.

?

In main document:

location.href = "products.html?prodType=" + loadCat;

In products.html:

var loadCat = new URL(document.URL).searchParams.get("prodType");

localstorage

In main document:

window.localStorage.setItem("prodType", loadCat);

In products.html:

var loadCat = window.localStorage.getItem("prodType");
noname
  • 291
  • 1
  • 12