Here is a script that reads in the url parameters (source):
HTTP_GET_VARS = [];
strGET = document.location.search.substr(1, document.location.search.length);
if (strGET !== '') {
gArr = strGET.split('&');
for (i = 0; i < gArr.length; ++i) {
v = '';
vArr = gArr[i].split('=');
if (vArr.length > 1) {
v = vArr[1];
}
HTTP_GET_VARS[unescape(vArr[0])] = unescape(v);
}
}
function GET(v) {
if (!HTTP_GET_VARS[v]) {
return 'undefined';
}
return HTTP_GET_VARS[v];
}
HTML
I put both ends in the same file. This reloads the page with the paramters set. Obviously you could do that without needing to reload if you stay on the same page.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form method="GET" action="index.html">
Troops: <input type="text" name="troops" value="0">
<input type="submit" value="send">
</form>
<script type="text/javascript">
document.writeln ('Troops: ' + GET('troops'));
</script>
</body>
</html>
Here is a plnkr to try it out.
EDIT: I changed the plnkr to have the exact same structure as your question with two separate files.
Since you want to use the value on several other pages the simple approach above might prove too limited. As you would have to send all the data again to the following page.
Although this is absolutely doable, one of the other suggested approaches might be more elegant.
DOM Storage
If you use a fairly modern browser (IE8+, FF3.5+, C4+) you can utilize DOM storage.
window.sessionStorage.setItem(field, value)
to save a value
window.sessionStorage.getItem(field)
to read a value
window.sessionStorage.removeItem(field)
to delete a value
window.sessionStorage.clear()
to delete everything
or in the same manner
localStorage.setItem(field, value)
localStorage.getItem(field)
localStorage.removeItem(field)
localStorage.clear()
The difference between sessionStorage
and localStorage
is that sessionStorage is limited to the current browser tab. localStorage is a little more persistent and can be accessed from any tab in the browser and depending on the browser and setting even in a completely new session.
Everything will be saved as a string! If you save a number, an integer for example you will need to parse it again after retrieval ( parseInt() ).
Here is a plnkr example using sessionStorage.
Cookies
Cookies are slightly more involved, on stackoverflow I found a link to this very nice overview.
Here is a plnkr using the very straight forward script provided by the afore mentioned quirksmode website.
createCookie(field, value, x)
saves the value to a cookie that is valid for x days
readCookie(field)
reads the value from the cookie
Note the the script.js in this plnkr is different from the one in the first plnkr!