-1

I am trying to set cookie in JavaScript when the user inputs in the textbox but it seems like its not working somehow. When I try to alert or console.log. I get "" value. Kindly help me with this.

HTML code:

<form action="confirm.html" id="interestForm" onsubmit="storeInHidden1()">
  <input type="text" name="userName">
  <input type="submit" value="Register">
</form>

JS code:

function storeInHidden1(){
   const queryString = window.location.search;
   const urlParams = new URLSearchParams(queryString);
   var queryStringDetails = urlParams.get("userName");
   document.cookie = "name=" + queryStringDetails;
   alert(document.cookie);
}
Rayees AC
  • 4,426
  • 3
  • 8
  • 31
Zuffido
  • 104
  • 1
  • 11

1 Answers1

0

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>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Chiel
  • 1,324
  • 1
  • 11
  • 30