The problem
Setting a cookie like
document.cookie = "name=" + variable
is according to w3schools a valid way of doing it. However the problem is that you are trying to acces url parameters that don't exist, which is the reason why your cookies are empty.
Suppose on example.com/index.html
you have the following form:
<form action="confirm.html" id="interestForm" onsubmit="storeInHidden1()">
<input type="text" name="userName">
<input type="submit" value="Register">
</form>
onsubmit
the code runs the function storeInHidden1()
which tries to get the window.location.search
which is still empty because nothing in your code sets the window.location.search
on example.com/index.html
.
Next according to action="confirm.html"
in the form, all of the data is send with a GET
request to (for example) example.com/confirm.html
. This url has now the parameters of ?userName=JohnDoe
. If you were now to run storeInHidden1
on this page you would in fact get some content in your cookie.
The solution
In order to save the username in a cookie on index.html
you would only have to change the code in storeInHidden1
. Instead of getting the username out of the url you would then get it directly from the form with document.getElementsByName("userName")[0].value
. The full code can be found below:
function storeInHidden1() {
var user = document.getElementsByName("userName")[0].value;
document.cookie = "name=" + user;
alert(document.cookie);
}
<form action="confirm.html" id="interestForm" onsubmit="storeInHidden1()">
<input type="text" name="userName">
<input type="submit" value="Register">
</form>