How to pass one variable to another page or same page?
So, Here I have given two file's code where one is data sending file. And another one is data receiving file if we transfer to another page.
index.html
<form action="#tp" method="get">
<input type="text" name="serialNumber" Value="rajnish" />
<input type="submit" value="Submit" />
</form>
<div id="tp">
<div id="data">
</div>
</div>
<script>
function processForm()
{
var parameters = location.search.substring(1).split("&");
var temp = parameters[0].split("=");
l = unscape(temp[1]);
document.getElementById("data").innerHTML = l;
}
processForm();
</script>
Here above code will be used only when you want to pass a variable on one page only.
<form action="#tp" method="get">
<input type="text" name="serialNumber" Value="rajnish" />
<input type="submit" value="Submit" />
</form>
Here, I have made one Form Tag for an get user's value in the input box. And for that, i have given form action to "tp" which is id name where the inputted data will show. And for that, we have to give Get/Post method to the form.
<div id="tp">
<div id="data">
</div>
</div>
And this the division where the data will print.
<script>
function processForm()
{
var parameters = location.search.substring(1).split("&");
var temp = parameters[0].split("=");
l = unscape(temp[1]);
document.getElementById("data").innerHTML = l;
}
processForm();
</script>
This script tag will fetch that information from URL. after function starts the 'parameters' variable store the search location value with the 'split("&")', Which is used for split the sentence with '&' symbol.
And next 'temp' variable will store the '0th parameters' with an 'split("=")'. and the 'l' will take the 1st value of 'temp' variable and give to 'data' id's element.
so, this was the code of one-page data transferring. But if you want to pass that data to another page then index page will be like:
index.html
<form action="action.html" method="get">
<input type="text" name="serialNumber" Value="rajnish" />
<input type="submit" value="Submit" />
</form>
so, here we have to just change the action's value to the page name.
and then action.html will contain rest of the code.
action.html
<div id="tp">
<div id="data">
</div>
</div>
<script>
function processForm()
{
var parameters = location.search.substring(1).split("&");
var temp = parameters[0].split("=");
l = unscape(temp[1]);
document.getElementById("data").innerHTML = l;
}
processForm();
</script>
So, here everything will be same as above. And you can now fetch that data to this page.
You can find this video tutorial of this as well by following:
If you have any questions and queries, comment us below.
Hey,
ReplyDeleteSo we are splitting the url by the '&' sign first but we wont have the '&' sign in our url as we are only passing the one value. Then will the code still work??
its not working
ReplyDelete