Setting cookies with form input

I am trying to create a cookie username using a user login on a web form. However, this does not work, and I do not know why. Do you know what the problem is?

<form> <input type="text" value="Enter Your Nickname" id="nameBox"> <input type="button" value="Go!" id="submit" onClick="putCookie"> <form> <script> var today = new Date(); var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days function setCookie(name, value){ document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString(); } //this should set the UserName cookie to the proper value; function storeValues(form){ setCookie("userName", form.submit.value); return true; } </script> </body> 
+6
source share
2 answers

You can check the code below, this may help you.

 <html> <head> <script> var today = new Date(); var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days function setCookie(name, value) { document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString(); } function putCookie(form) //this should set the UserName cookie to the proper value; { setCookie("userName", form[0].usrname.value); return true; } </script> </head> <body> <form> <input type="text" value="Enter Your Nickname" id="nameBox" name='usrname'> <input type="button" value="Go!" id="submit" onclick="putCookie(document.getElementsByTagName('form'));"> </form> </body> </html> 

While the specific function name should be putCookies instead of storeValues ​​and the function call, you can do this: putCookie (document.getElementsByTagName ('form'));

Inside the function definition, cookie values ​​can be obtained from the form, as shown below: setCookie ("userName", form [0] .usrname.value);

The form element must have the attribute: name = 'usrname'

He will set cookies for your username using the form element.

+5
source

Change the form to:

 <form onsubmit="storeValues(this)"> <input type="text" value="Enter Your Nickname" id="nameBox"> <input type="submit" value="Go!" id="submit"> <form> 

And the storeValues ​​(form) function for:

 { setCookie("userName", form.nameBox.value); return true; } 
0
source

Source: https://habr.com/ru/post/987810/


All Articles