---
title: "How to setting a cookie with the contents of a textbox?"  
description: "How to setting a cookie with the contents of a textbox?"  
author: "Amit Singh"  
published: 2011-03-18  
updated: 2020-09-21  
canonical: https://www.mindstick.com/interview/528/how-to-setting-a-cookie-with-the-contents-of-a-textbox  
category: "javascript"  
tags: ["javascript"]  
reading_time: 1 minute  

---

# How to setting a cookie with the contents of a textbox?

Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy "escape()" function to encode the values, and "unescape()" to retrieve them.\
\
//Sets cookie of current value for myTextBox\
function TextBoxOnchange() {\
var myBox = window.document.getElementById(myTextBox");\
document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString();\
}\
\
//return a string like ";expires=Thu, 5 Jan 2011 16:07:52 UTC"\
function getExpirationString() {\
var exp = new Date();\
var threemonths = exp.getTime()+(120*24*60*60*1000);\
exp.setTime(threemonths);\
return ";expires="+exp.toGMTString();\
}\
\
This is called from the event handler in the HTML.\
\
<input name="myTextBox" type="text" id="myTextBox"\
onchange="javascript:TextBoxOnchange()" />

## Answers

### Answer by Amit Singh

Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy "escape()" function to encode the values, and "unescape()" to retrieve them.\
\
//Sets cookie of current value for myTextBox\
function TextBoxOnchange() {\
var myBox = window.document.getElementById(myTextBox");\
document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString();\
}\
\
//return a string like ";expires=Thu, 5 Jan 2011 16:07:52 UTC"\
function getExpirationString() {\
var exp = new Date();\
var threemonths = exp.getTime()+(120*24*60*60*1000);\
exp.setTime(threemonths);\
return ";expires="+exp.toGMTString();\
}\
\
This is called from the event handler in the HTML.\
\
<input name="myTextBox" type="text" id="myTextBox"\
onchange="javascript:TextBoxOnchange()" />


---

Original Source: https://www.mindstick.com/interview/528/how-to-setting-a-cookie-with-the-contents-of-a-textbox

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
