2

I am learning js, recently, I apologize for my English and for the obviousness of my questions. I have two problems, I would appreciate solutions in pure JavaScript.

Following several tutorials, I installed a localStorage script in an HTML page.


pag1.html

 <p> Hello! what's your name?</p>

 <form action="pag2.html">
  <input type="text" id="txt"/>
  <input type="submit" value="nome" onClick="passvalues();"/>
 </form>
 // the form has a link to pag2.html

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

Let's say the user enters the name "Lucy":


pag2.html

<p>Hi <span id="result">Lucy<span> nice to meet you!</p>`  // the name appears

<p>How are you today <span id="result">NOTHING</span>?</p>` // the name does not appear

<a href="pag3.html">pag3</a>

<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue"); 
</script>

First Question

the NAME appears only once for my mistake or must it be so? Should I use another syntax to make it appear several times?


pag3.html

<p><span id="result">Lucy</span>which gender designation do you prefer to be used with you?</p>

<p><a href="male.html">male</a></p>

<p><a href="female.html">female</a></p>

<p><a href="neutral.html">neutral</a></p>

<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue"); 
</script>

Second Question

In pag 3 the user has to choose whether he wants to be called male, female or neutral.

One solution is to set three different pages according to the genre chosen. But this solution is not elegant and inflates the number of pages.

I seem to have read somewhere that with js it is possible to go to another page and at the same time set the value of a Boolean variable (true / false) through a link.

Something like this (the syntax is invented):

<a href="female.html" set var f true> female</a>

This would allow you to create a single landing page with the insertion of three "if":

 if (female true) {
    text = "brava";
  } else if (male true) {
    text= "bravo";
  } else {
    text = "bene";
  }

Is it possible to do this? How? I have tried this script htmlgoodies several times but it is too difficult for me.

Hello,

First of all I'd thank @cssyphus and @Shahnawazh for the answers.

Question 1

I managed to show the name several times on the same page with the script:

<script>
 var result = document.getElementsByClassName('result');

[].slice.call(result).forEach(function (className) {
            className.innerHTML = localStorage.getItem("textvalue");
 });
 </script>

But, do I really need to include it on all pages that need to show the name? I also tried to insert the script into an external js page but the name did not appear even once.

Question 2

As for the second question, I did not get positive results.

Meimei
  • 165
  • 6

2 Answers2

1

Rather than using id, you can use class for showing result because id is unique. Also for storing male, female or neutral you can use radio buttons, and when you click any of them, just save the result in the localStorage. Here are the three pages.

page1.html

<body>
    <p> Hello! what's your name?</p>

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

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

</body>

page2.html

<body>
    enter code here
    <p>Hi <span class="result">Lucy<span> nice to meet you!</p>

    <p>How are you today <span class="result"></span>?</p>

    <a href="page3.html">page3</a>

    <script>

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

        [].slice.call(result).forEach(function (className) {
            className.innerHTML = localStorage.getItem("textvalue");
        });

    </script>
</body>

page3.html

<body>
    <p><span class="result"></span> which gender designation do you prefer to be used with you?</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>You've selected <span class="selectedGender"></span></p>

    <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>
</body>
Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24
  • Thanks for your answer, unfortunately due to page layout reasons I can't use radio buttons. However I will save your code for future use (it's always handy to have a radio button on hand). – Meimei Jul 12 '20 at 09:33
  • It's alright. You can see [my answer here](https://stackoverflow.com/questions/59171789/how-to-redirect-to-a-page-and-then-execute-a-jquery-function-call/59172248#59172248) that how can you pass parameters from one page to another. You can do it by this way in your case. – Shahnawaz Hossan Jul 12 '20 at 09:40
  • thanks, I read your solution but it's really too complicated for me – Meimei Jul 12 '20 at 14:42
  • Ok, sorry for that. – Shahnawaz Hossan Jul 12 '20 at 14:47
  • Hello @shahnawazh, after receiving some clarifications I decided to choose your answer as the correct answer, thanks for help. – Meimei Jul 14 '20 at 15:12
  • @Meimei, My pleasure to help you :) – Shahnawaz Hossan Jul 14 '20 at 15:14
  • Hi @cssyphus sorry if i bother you. for "pass" the localstorage to another html page I did, it does not work. Could you help me please? plus var result = document.getElementsByClassName('result'); [].slice.call(result).forEach(function (className) { className.innerHTML = localStorage.getItem("textvalue"); }); – Meimei Jul 17 '20 at 14:28
0

You have just discovered why you cannot have two elements on the same page with the same ID - only the first one will work. However, classes work almost exactly like IDs, so just use the same className at both locations:

<p>Hi <span class="result">Lucy<span> ...
...
<p>How are you today <span class="result">Lucy</span> ...

As to your second problem, just use localStorage again. Set a different localStorage variable and read/write that.

However, what you are probably thinking of is using a query string, like this:

<a href="person.html?gender=f">female</a>

See this SO question for information and code examples.

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Hi @cssyphus your suggestion: female; it's interesting but I don't know how to insert it in the script and also I would like a solution pure javascript. But I don't know how to make a link pressure set a localStorage. I could just do is that each link points to a different page and each page has manually set its gender: but this is not javascript and it is not very elegant. Do you have some suggestions? Thanks for the attention. – Meimei Jul 14 '20 at 10:18
  • @Meimei Shahnawaz Hossan's answer shows you how to use a link to set a localStorage variable. Use the same algorithm that Shahnawaz used in his code example to ALSO set the person's gender. I think using localStorage is is the best solution for you - using the query strings will be too complicated for your current skill level. **Please consider accepting Shahnawaz's answer as the correct answer** -- it has everything that you need to solve both problems. – cssyphus Jul 14 '20 at 13:11
  • Thanks a lot for the clarifications. – Meimei Jul 14 '20 at 14:48
  • Hi @cssyphus I tried pass localstorage to another page. It does not work. Help me please. sp class="selectedGender">/sp sp class="result"> /sp var selectedGender = document.getElementsByClassName('selectedGender'); ....... plus: var result = document.getElementsByClassName('result');...... – Meimei Jul 17 '20 at 14:39
  • You don't need to **pass** localStorage to another page. All pages on the same domain have access to the same localStorage area. If you `.set` a variable called `username` (contents: "Bob") on page 1, you can `.get` that variable from any other page, just using `var name = localStorage.getItem("username")` *(so now, on that page, the var `name` contains the value `Bob`)*. You can read that localStorage variable from any page you create. – cssyphus Jul 17 '20 at 15:48
  • Thanks. Sorry my mistake, I meant that I can't pass the var to another page. I tried as you showed me by replacing id with class. But it does not work. I understand that I'm too old for these things and I missed the train.. – Meimei Jul 17 '20 at 18:04
  • @meimei Not at all... Since this question has been answered, please open another question and post your current code, then reply to this comment with a link to the new question. We'll get you sorted, no worries. – cssyphus Jul 17 '20 at 19:46
  • Hi, thsnkd for the tip, the new post is here: https://stackoverflow.com/questions/62969431/setting-a-var-in-localstorage-from-button-radio-and-pass-it-to-other-pages – Meimei Jul 18 '20 at 14:00