36

I'm new to HTML and JavaScript, what I'm trying to do is from an HTML file I want to extract the things that set there and display it to another HTML file through JavaScript.

Here's what I've done so far to test it:
testing.html

<html>
<head>
   <script language="javascript" type="text/javascript" src="asd.js"></script>
</head>

<body>

<form name="form1" action="next.html" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>

</body>
</html>

next.html

<head>
   <script language="javascript" type="text/javascript" src="asd.js"></script>
</head>

<body>

<form name="form1" action="next.html" method="get">
<table>
    <tr>
        <td id="here">test</td>
    </tr>
</table>
</form>

</body>
</html>

asd.js

function testJS()
{

var b = document.getElementById('name').value

document.getElementById('here').innerHTML = b;

}

test.html -> ads.js(will extract value from the test.html and set to next.html) -> next.html

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
newbie
  • 527
  • 2
  • 8
  • 13

11 Answers11

47

Try this code:

In testing.html

<script>
function testJS() {
    var b = document.getElementById('name').value,
        url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);
    
    document.location.href = url;
}
</script>

And in next.html:

<script>
window.onload = function () {
    var url = document.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('here').innerHTML = data.name;
}
</script>   

Description: JavaScript does not have any specific feature to share data between different pages. However, there are some alternative ways to achieve it, e.g., using URL Parameters (I have used this approach in my code), cookies, localStorage, etc.

At first in the testing.html, store the name parameter in URL (?name=...). Then in the script of next.html, parse the URL and get all the params from previous page.

PS. I'm a non-native English speaker, will you please correct my message, if necessary.

Alex Fitiskin
  • 755
  • 4
  • 6
  • You can use external JS, for example, `test.js`. Include in this file 2 functions: `testJS` (code block 1) and `onLoad` (code block 2, but replace `window.onload = function` with `function onLoad`). In `testing.html` bind `testJS` function to button click action (`onClick="testJS()"`) and in `next.html` bind `onLoad` function to body onload action (`onload="onLoad"`) – Alex Fitiskin Jul 06 '13 at 12:15
  • 1
    You're a genius. – Shounak Ray Jun 16 '19 at 18:55
  • @ShounakRay can you please elaborate this code for me? I'm a beginner and I'm trying to achieve something similar in my practice but I am a little confused here. – noob87 Jul 06 '21 at 06:54
25

The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie. The modern way is to use Local Storage, which has a good browser support (IE8+, Firefox 3.5+, Chrome 4+, Android 2+, iPhone 2+). Using localStorage is as easy as using an array:

localStorage["key"] = value;

... in another page ...
value = localStorage["key"];

You can also attach event handlers to listen for changes, though the event API is slightly different between browsers. More on the topic.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
13

Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.

Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:

  1. Session Cookies
  2. HTML5 LocalStorage
  3. POST the variable in the url and retrieve them in next.html via window object
SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59
Shreyas
  • 367
  • 3
  • 9
8

With the Javascript localStorage class, you can use the default local storage of your browser to save (key,value) pairs and then retrieve these values on whichever page you need using the key. Example - Pageone.html -

<script>
    localStorage.setItem("firstname", "Smith");
</script>  

Pagetwo.html -

<script>
    var name=localStorage.getItem("firstname");
</script>  
5

you can simply send the data using window.location.href first store the value to send from testing.html in the script tag, variable say

<script> 
  var data = value_to_send
  window.loaction.href="next.htm?data="+data
</script>

this is sending through a get request

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Abhishek Tripathi
  • 1,570
  • 3
  • 20
  • 32
5

I use this to set Profile image on each page.

On first page set value as:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
prashant kute
  • 333
  • 4
  • 9
2

HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed

document.getElementById('here').innerHTML = data.name; 

This needed to be changed to

document.getElementById('here').innerHTML = data.n;

I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .

0
<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>

<body>

<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>

</body>

client side scripting

function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}

jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.

jquery load function http://api.jquery.com/load/

myk.
  • 323
  • 1
  • 5
0

The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.

1) page1.html

<!-- Value passing one page to another 
     Author: Codemaker
-->
<html>
    <head>
        <title> Page 1 - Codemaker</title>
    </head>
    <body>
        <form method="get" action="page2.html">
            <table>
                <tr>
                    <td>First Name:</td>
                    <td><input type=text name=firstname size=10></td>
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td><input type=text name=lastname size=10></td>
                </tr>
                <tr>
                    <td>Age:</td>
                    <td><input type=text name=age size=10></td>
                </tr>
                <tr>
                    <td colspan=2><input type=submit value="Submit">
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

2) page2.html

<!-- Value passing one page to another 
     Author: Codemaker
-->

<html>
    <head>
        <title> Page 2 - Codemaker</title>
    </head>
    <body>
        <script>
            function getParams(){
                var idx = document.URL.indexOf('?');
                var params = new Array();
                if (idx != -1) {
                    var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
                    for (var i=0; i<pairs.length; i++){
                        nameVal = pairs[i].split('=');
                        params[nameVal[0]] = nameVal[1];
                    }
                }
                return params;
            }
            params = getParams();
            firstname = unescape(params["firstname"]);
            lastname = unescape(params["lastname"]);
            age = unescape(params["age"]);
            document.write("firstname = " + firstname + "<br>");
            document.write("lastname = " + lastname + "<br>");
            document.write("age = " + age + "<br>");
        </script>
    </body>
</html>
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81
  • 1
    how can I pass these values outside of script block? below example ```

    Pluralsight Training:PS:- Bank Account Details

    PS: Bank Account Details

    params = getParams();

    Account # : params["accountNo"]

    Account Holder Name : params["accountHolderName"]

    Balance : params["balance"]

    ```
    – sri hari kali charan Tummala Jun 26 '19 at 19:59
0

I coded the answers from Alex Fitiskin, and added a bit of extra code. I added a parameter to the onLoad function to get the form's submit event, and prevent it's default behaviour first.

Here's the code:

test.html

<html>
<head>
    <script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
    <form name="form1" action="next.html" method="get" onsubmit="return testJS(event)">
        name:<input type="text" id="name" name="n">
        <input type="submit" value="next">
        <!-- <button type="button" id="print" onClick="testJS()"> Print </button> //Button not needed anymore -->
    </form>
</body>
</html>

next.html

<head>
    <script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
    <form name="form1" action="next.html" method="get">
        <table>
            <tr>
                <td id="here">test</td>
            </tr>
        </table>
    </form>
</body>
</html>

test.js

function testJS(e) {
    e.preventDefault();
    var b = document.getElementById('name').value,
        url = 'http://path_to_next_location/next.html?name=' + encodeURIComponent(b);

    document.location.href = url;
}

function onLoad() {
    var url = document.location.href,
        params = url.split('?')[1].split('&'),
        data = {},
        tmp;
    for (var i = 0, l = params.length; i < l; i++) {
        tmp = params[i].split('=');
        data[tmp[0]] = tmp[1];
    }
    document.getElementById('here').innerHTML = data.name;
}

window.onload = onLoad;

This way the onload function will be replaced with the custom onLoad function, and the form will not be submitted the default way, but instead using the code inside the testJS function.

0

Avoid localstorage use as data are not safe with get method. Best option is to use script set to module and then export & import data via 2 js files to html file. Variable value can be passed between pages using module method.