Is it possible to name a cookie in javascript?

i've got a web program that will display

"name:undefined Name:Jack Grade:32"

whenever i display the contents of a cookie i create. i'm assuming th first bit is the cookie name itself and then the other two bits are the contents?

also, when i try to add a new bit to the cookie it just overwrites it, is their a way i can add it to the end of this one. so it displays

name:undefined Name:Jack Grade:32
name:undefined Name:Billy Grade:72

???

here is the code i have

<script type="text/javascript">
function WriteCookie()
{

	var allowed=/^[a-zA-Z]+$/;

	if(document.gradeAdd.studentName.value.match(allowed))
	{

		cookievalue=escape(document.gradeAdd.studentName.value)+";";
		cookievalue2=escape(document.gradeAdd.studentGrade.value)+";";
		document.cookie="Name = " + cookievalue;
		document.cookie="Grade = " + cookievalue2;
		alert(document.cookie);
	}
	else
	{
		alert("Enter a valid name");
		return;
	}
}

function ReadCookie()
{
   var allcookies = document.cookie;
   // Get all the cookies pairs in an array
   cookiearray  = allcookies.split(';');

   // Now take key value pair out of this array
   for(var i=0; i<cookiearray.length; i++)
  {
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
	  document.write(name + ":" + value);
  }
}
</script>

Dani AI

Generated

Yes — cookies are name=value pairs. The odd output here (the leading "undefined" and merged fields) is symptomatic of how the cookie string is being written and parsed in the original code: adding semicolons into the value and placing spaces around the = will produce extra tokens when splitting document.cookie. Also avoid escape() (deprecated); use encodeURIComponent/decodeURIComponent when storing and reading values.

As ’s snippet shows, manually appending ; to the value and using "Name = ..." will confuse simple split-based parsing. As pointed out, set cookie attributes (path/expiry) when needed. For multiple student records the options are:

  • give each record a unique cookie name (e.g., student_1_name, student_1_grade), or
  • keep a single cookie whose value is a JSON array (watch the size limit), or
  • store the list in localStorage (recommended for client-only data).

Safe helper example (uses encoding, trims tokens, and uses max-age instead of raw semicolon tricks):

function setCookie(name, value, days) {
  var entry = encodeURIComponent(name) + "=" + encodeURIComponent(value);
  if (typeof days === "number") entry += ";max-age=" + (days * 24 * 60 * 60);
  entry += ";path=/";
  document.cookie = entry;
}

function parseCookies() {
  return document.cookie.split(';').reduce(function(map, pair) {
    var parts = pair.split('=');
    var k = decodeURIComponent(parts.shift().trim());
    var v = decodeURIComponent(parts.join('=').trim() || "");
    map[k] = v;
    return map;
  }, {});
}

For client-side lists, prefer localStorage to avoid the ~4KB-per-cookie limit and the fact cookies are sent to the server on every request. Example: store an array with localStorage.setItem('students', JSON.stringify(array)) and read it back with JSON.parse(...).

Further reference: MDN on document.cookie and Web Storage for current best practices:
Document.cookie
localStorage
Cookie size limits

Is it possible to name a cookie in javascript?

i've got a web program that will display

"name:undefined Name:Jack Grade:32"

whenever i display the contents of a cookie i create. i'm assuming th first bit is the cookie name itself and then the other two bits are the contents?

also, when i try to add a new bit to the cookie it just overwrites it, is their a way i can add it to the end of this one. so it displays

name:undefined Name:Jack Grade:32
name:undefined Name:Billy Grade:72

???

here is the code i have

<script type="text/javascript">
function WriteCookie()
{

	var allowed=/^[a-zA-Z]+$/;

	if(document.gradeAdd.studentName.value.match(allowed))
	{

		cookievalue=escape(document.gradeAdd.studentName.value)+";";
		cookievalue2=escape(document.gradeAdd.studentGrade.value)+";";
		document.cookie="Name = " + cookievalue;
		document.cookie="Grade = " + cookievalue2;
		alert(document.cookie);
	}
	else
	{
		alert("Enter a valid name");
		return;
	}
}

function ReadCookie()
{
   var allcookies = document.cookie;
   // Get all the cookies pairs in an array
   cookiearray  = allcookies.split(';');

   // Now take key value pair out of this array
   for(var i=0; i<cookiearray.length; i++)
  {
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
	  document.write(name + ":" + value);
  }
}
</script>

There is a brilliant guide to cookie work available at http://www.quirksmode.org/js/cookies.html.

For me, cookies have only worked when I've done:

document.cookie = "cookieName=cookieValue; expires=Mon, 4 Apr 2011 14:16:10 UTC; path=/"

so you could try:

document.cookie = "Name=Joe; expires=Mon, 4 Apr 2011 14:16:10 UTC; path=/"

. YMMV though and I recommend familiarising yourself with the Quirksmode stuff.

Thanks, i'll give it a try!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.