How to pass the value of a variable to another HTML document in Javascript?

Asked

Viewed 161 times

-1

In an HTML file I have a variable created in Javascript called vidadps and I want to pass its value to another HTML document. How can I do this in Javascript ?

Inside the initial HTML:

<script>
    var vidainit = 100
    var dano = 20
    var vidadps = vidainit - dano
</script>

Inside the other HTML document:

<script>
    function obterValor(){
        // Função para retornar o valor do HTML anterior
    }
    
    var vidadps = obterValor()
</script>

1 answer

1


Yes is possible. You can pass several values in the URL of your other html document using the tabs ? or #.

If you choose to use #, you must get the values in the other document by location.hash and if you choose to use ?, you must get the values by location.search. See this example below:

Inside the index.html file:

<script>
    var valor = 345;
    location.assign("outroHTML.html#" + valor);
</script>

Inside another HTML.html file:

<script>
    var valor = location.hash.split("#")[1];
    console.log(valor);
</script>

What the location.hash and the location.search do is return the values passed in the URL as a string. In the example I used the split("#") because it returns values with tabs.

The same thing would happen too if I used the search. See how it would look:

<script>
    var valor = location.search.split("?")[1];
    console.log(valor);
</script>

Since the return of this is a String, after you have obtained the value you should convert it to integer. And remember that it’s always good to check what type of value was passed in the URL before taking any action.

  • Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.