2

This discussion is the spin off of this post:passing-variables-between-pages,

I have edited the question in order to provide More clarity on the scripts, please who will give any answers to use denomination used in this version.

A.html

 <form action="b.html">  // username field, let's say "Macbeth"
 <input type="text" id="txt"/>
 <input type="submit" value="nome" onClick="passvalues();"/>
 </form>

<span id="result">Macbeth</span> // display username 

<script>
 function passvalues()   
 {
  var nme = document.getElementById("txt").value;  // set var username  nme = textvalue
  localStorage.setItem("textvalue", nme);
  return false;
  }
  </script>

It works set localStorage and display it.

B.html

// show the username multiple times in an html text.

<p><strong><span class="result">Macbeth</span></strong>, Nice name! 
It's the first time I've heard it! mmm...and tell me<strong>Macbeth<span  class="result"></span></strong> which gender you are?</p>

<form name="genderForm" action=""> 
    <input type="radio" name="gender" value="male"> Male<br>
    <input type="radio" name="gender" value="female"> Female<br>
    <input type="radio" name="gender" value="neutral"> Neutral
    </form>

// form to obtain the gender chosen by the user, let's say "male"
`<p>I am a <span class="selectedGender"></span> of course!</p>` 
   // display the selected gender

<script>
   var result = document.getElementsByClassName('result');
   [].slice.call(result).forEach(function (className) {
    className.innerHTML = localStorage.getItem("textvalue");
    });
    var rad = document.genderForm.gender;
    var prev = null;
    for (var i = 0; i < rad.length; i++) {
    rad[i].addEventListener('change', function () {
    (prev) ? console.log(prev.value) : null;
    if (this !== prev) {
    prev = this;
    }
    console.log(this.value);
    document.getElementsByClassName("selectedGender")[0].innerHTML =   this.value;
        localStorage.setItem("gender", this.value);
        });
        }
        </script>

<script>
var selectedGender = document.getElementsByClassName('selectedGender');
{
className.innerHTML = localStorage.getItem("textvalue");
};
</script>

It works, display the selected gender.

C.html

I am really, really sorry but I am completely lost and confused here. I tried several times one of the suggested by solutions:

<span id="welcome"></span> to page 4 <span id="name"></span>
<script>
var username = localStorage.getItem("textvalue");
var usergender = localStorage.getItem("gender");
document.getElementById('name').innerHTML = username;
document.getElementById('gender').innerHTML = usergender;
if (usergender === 'female'){
document.getElementById('welcome').innerHTML = 'brava';
}else if (usergender === 'male'){
document.getElementById('welcome').innerHTML = 'bravo';
}else{
document.getElementById('welcome').innerHTML = 'bene';
 }
 </script>

I know I'm a hopeless case, I don't understand it.

  • In which page do I have to insert this script?
  • this script replaces the previous ones?

Can't I use the same scripting used for the username?

1 - get the choice:"selectedgender"

2 - display it with (of course changing the elements names)

<script>
 function passvalues()   
 {
  var nme = document.getElementById("txt").value;  // set var username  nme = textvalue
  localStorage.setItem("textvalue", nme);
  return false;
  }
  </script>

3 - and show with:

<span id="result">Macbeth</span>  // display username

Thanks for the attention.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Meimei
  • 165
  • 6
  • 1
    It's hard to understand what's going from the code you posted. However, you're setting the gender under `gender` key in localStorage (`localStorage.setItem("gender", this.value);`) but later you're trying to get the value for gender with `textvalue` key. Try to get gender using the same key e.g. `localStorage.getItem("gender");` – Yos Jul 18 '20 at 14:30
  • Thanks for you comment. I posted the link of the orginal post, check it .It works but just for the first page. I tried with "gender" to , nothing. – Meimei Jul 18 '20 at 14:43
  • 1
    did you try using the same `gender` key in `getItem`? – Yos Jul 18 '20 at 14:44
  • 1
    @Meimei See my answer below. Hitesh's answer is also correct, so you should upvote it (not the same as choosing the correct answer). On StackOverflow there are two ways to say thanks: upvoting and checkmark. **Neither one costs you anything, but each one gives a reward to the person who wrote the answer.** If you ***really*** like an answer, you can **both** upvote it (up triangle) **and** choose it as correct (checkmark). You can only checkmark one answer, but you can upvote as many as you want *(and again, upvoting doesn't cost you anything).* You cannot upvote before you have 15 points – cssyphus Jul 19 '20 at 23:02
  • Hi @cssyphus, the space for comments is very limited, so I edited the question to clarify my problems. Your solution is excellent but I can't use it. About "nifty bit of code", if i delete it the whole script doesn't work (my fault of course), regards. – Meimei Jul 20 '20 at 10:47
  • It is a Kafkian situation that yesterday among the hundreds of tests I did, one showed the word "bene" (for the if gender neutral). But I canceled that test because I thought it was a mistake. – Meimei Jul 20 '20 at 11:07

3 Answers3

1

Your page3.html can be as below:

<!DOCTYPE html>
<html>
<head>
    <title>Page 3</title>
</head>
<body>
    <p><span id="name"></span>, please select your gender.</p>
    <a id="Male" href="page4.html" onclick="saveSelectedGender(this)">Male</a><br/>
    <a id="Female" href="page4.html" onclick="saveSelectedGender(this)">Female</a><br/>
    <a id="Neutral" href="page4.html" onclick="saveSelectedGender(this)">Neutral</a><br/>
    <script>
        document.getElementById('name').innerHTML = localStorage.getItem("textvalue");

        function saveSelectedGender(ele) {
            localStorage.setItem('gender', ele.id);
        }
    </script>
</body>
</html>

and your page4.html can be as below:

<!DOCTYPE html>
<html>
<head>
    <title>Page 4</title>
</head>
<body>
    <p><span id="name"></span>, your selected gender is: <span id="gender"></span>.</p>
    <script>
        document.getElementById('name').innerHTML = localStorage.getItem("textvalue");
        document.getElementById('gender').innerHTML = localStorage.getItem("gender");
    </script>
</body>
</html>
  • Hello @hitesha, thanks for the reply, it is useful that the result is shown on a later page, but I was looking for the way to set the localStorage. – Meimei Jul 19 '20 at 12:27
1

Notice this line on page two:

localStorage.setItem("gender", this.value);

It is almost exactly the same as the line on page 1 that stores the user name:

localStorage.setItem("textvalue", nme);
 

In your hidden localStorage, you now have two variables: gender and textvalue, and each of them stores some information. Check it for yourself - there is a way to view the localStorage area:

INSTRUCTIONS FOR GOOGLE CHROME:
 1. Run your app, and enter the data on both page 1 and page 2.
 2. Press <kbd>F12</kbd> (or, right-click on the page and choose `Inspect Element`)
 3. "Developer Tools" will open. 
 4. Note the menu at top that begins: `Elements | Console | Sources | Network >>`
      If the last menu item is `>>` then click that - additional menu choices will drop-down
 5. You want the menu item `Application` - click on that
 6. You will see 5 groupings on the left: Application, Storage, Cache, Background... etc
 7. In the Storage group, do you see `Local Storage`? That's what we want!
 8. Click the drop-down triangle beside (at the left) "Local Storage"
 9. Now, in the right side panel, you should see your "hidden" variables, and their current values
 

No matter what HTML page you are on (of your project), you can see those same variables - so you can tell your script to read those variables.

So, on pages 3 and 4, write some javascript (the code is below) that will:
(a) read a localStorage value and store it in a new variable
(b) select the appropriate element (div, span, p, etc) on that page
(c) stick the variable data into the element.
(d) repeat for the other localStorage entry

The reason why the existing javascript code didn't work is because it was written for page2, where the target element is called class="result". Note the first line of the javascript:

var bob = document.getElementsByClassName('result');
 

(I changed the name of the variable because that name doesn't matter - what matters is getElementsByClassName('result')). If there is no element on the page with class="result", the javascript will fail right there. So, on pages 3 and 4, death!

On page 4, then, you can do this:

<span id="welcome"></span> to page 4 <span id="name"></span>
<script>
    var username = localStorage.getItem("textvalue");
     var usergender = localStorage.getItem("gender");
     document.getElementById('name').innerHTML = username;
     document.getElementById('gender').innerHTML = usergender;
     if (usergender === 'female'){
         document.getElementById('welcome').innerHTML = 'brava';
     }else if (usergender === 'male'){
         document.getElementById('welcome').innerHTML = 'bravo';
     }else{
         document.getElementById('welcome').innerHTML = 'bene';
     }
 </script>

Final Notes:

The reason you do not need this nifty bit of code:

[].slice.call(result).forEach(function (className)...

is because THIS code var result = document.getElementsByClassName('result')

creates a list (an array) of all the elements with the className result. Then the .slice code loops through that array and schleps the username into each and every element.result. Only on page 2 do you have an element (well, two elements) with the className "result". On page 3 (NO className "result") elements, the code fails.

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Hi @cssyphus , thanks for the tutorial / answer, I converted it to pdf to read it better. I'm studying it to put it on the pages (I have reaction times as a chess player). – Meimei Jul 19 '20 at 12:37
1

To make life a little easier for you, I re-wrote your scripts using slightly different variable names that make a little more sense. I tested these; they work. If you print both sets and compare these NEW scripts with the older scripts, you can see a little more clearly how it all works.

Page A:

<form action="b.html">
    <input type="text" id="txt"/>
    <input type="submit" value="nome" onClick="passvalues();"/>
</form>

<span id="result"></span>

<script>
    function passvalues(){
        var nme = document.getElementById("txt").value;  // set var username  nme = youzer
        localStorage.setItem("youzer", nme);
        return false;
    }
</script>

Page B:

<!-- show the username multiple times in an html text. -->
<p>Hello, <strong><span class="uname">Macbeth</span></strong>, Nice name!</p>
<p>It's the first time I've heard it! mmm...and tell me, <strong><span class="uname"></span></strong>, which gender you are?</p>

<form name="genderForm" action=""> 
    <input type="radio" name="gender" value="male"> Male<br>
    <input type="radio" name="gender" value="female"> Female<br>
    <input type="radio" name="gender" value="neutral"> Neutral
    </form>

<p>I am a <span class="selectedGender"></span> of course!</p>

<script>
   /* Schlep stored name into all elements with className "uname" */
   var unamez = document.getElementsByClassName('uname');
   [].slice.call(unamez).forEach(function (className) {
      className.innerHTML = localStorage.getItem("youzer");
   });

   var frmGender = document.genderForm.gender;
   var prev = null;
   for (var i = 0; i < frmGender.length; i++) {
      frmGender[i].addEventListener('change', function () {
         (prev) ? console.log(prev.value) : null;
         if (this !== prev) {
            prev = this;
         }
         console.log(this.value);
         document.getElementsByClassName("selectedGender")[0].innerHTML = this.value;
         localStorage.setItem("gender", this.value);
         //Delay 2 seconds, then go to page (C)
         setTimeout(function(){
            window.location.href = 'c.html';
         },2000);
      });
   }
</script>

Page C:

<span id="greetz"></span> to page 4, <span id="name"></span>!
<p></p><a href="a.html">Return to page A</a></p>

<script>
   var username = localStorage.getItem("youzer");
   var usergender = localStorage.getItem("gender");
   document.getElementById('name').innerHTML = username;
   // Below commented out because <span id="gender"> does not exist on page
   // document.getElementById('gender').innerHTML = usergender;

   if (usergender === 'female'){
      document.getElementById('greetz').innerHTML = 'Brava';
   }else if (usergender === 'male'){
      document.getElementById('greetz').innerHTML = 'Bravo';
   }else{
      document.getElementById('greetz').innerHTML = 'Bene';
   }
</script>

Note that these code snippets don't "work" on StackOverflow - the Run Code Snippet buttons won't do anything. I used the Code Snippet system only to allow the three code groups to be hidden until expanded, for neatness. You must copy each one out and paste it into a file in your dev environment to make them work (all three must be present on your system before running them).

cssyphus
  • 37,875
  • 18
  • 96
  • 111