How to use cookie

In web application, sometimes, you have to use cookie no matter client cookie or server cookie to store values you want to save. I summarised as below.

Usage 1: Create per cookie per value
Initialize cookie:
HttpCookie cookie = new HttpCookie(“UserName”);
cookie.Value = “admin”;
Response.AppendCookie(cookie );

Retrieve cookie:
HttpCookie cookie = Request.Cookies(“UserName”);
cookieValue = cookie.Value;
Response.AppendCookie(cookie );

If add cookie from server side:
Response.Cookies.Add(new HttpCookie(“UserName”, “admin”)); //add particular cookie into cookie colliections
Retrieve cookie:
cookieValue = Response.Cookies[“UserName”].Value;

Usage 2: Add all values to one cookie object

HttpCookie cookie = Request.Cookies(“Default”);
cookie.Values.Add(“userid”, “1”); || cookie[“userid”] = “1”; //both syntax work
cookie.Values.Add(“username”, “admin”);

HttpCookie cookie = Request.Cookies(“Default”);
cookieValue = cookie.Values[“userid”];

Basic cookie operations: (create, add value, retrieve and delete)

1. js store cookie

<script type="javascript">
function setCookie(name,value){ //name is cookie's name, value is name's value
         var days = 10; //stored days and can passed by parameters
         var expires = new Date(); //create date variable
         expires.setTime(expires.getTime() + days * 30 * 24 * 60 * 60 * 1000); //expires time = current time + expired time (seconds)
         var str = name + '=' + value +';expires=' + expires.toGMTString(); //store value and expire date time to the cookie(need GMT format to display date string)
         var str = name + '=' + escape(value) +’;expires=’ + expires.toGMTString();                  document.cookie = str; }

The following is the generic cookie

<script type="text/javascript" language="JavaScript">//
function addCookie(name,value,expireHours){
           var cookieString=name+"="+escape(value);
           if(expireHours>0){ //check if setup the date time
           var date=new Date(); 
           cookieString=cookieString+"; expire="+date.toGMTString(); 

Notes: Should use escape() function to encode, it could encode special characters to HEX, such as space will compiled to “20%” and able to save into cookie, nevertheless, it could avoid issues in multiple language environment
document.cookie=”str=”+escape(“I love js”);
after encode:
But after encode by escape(), the value needs to revoke unescape()to decode and retrieve the original cookie value

2. js retrieve cookie value

a.general loop characters retrieve

function getCookie(name){
var strcookie = document.cookie;// get cookie string
var arr = strcookie.split(‘;’); //split cookie
for(var i = 0;i&lt;arr.length;i++){
var arrStr = arr.split(‘=’); //split specific cookie
if(arrStr[0] == name) return arrStr[1]; //check if cookie name existing and output
return "";

b.use unescape to get cookie value

function getCookie(name){
var _password = document.getElementById(‘password’);
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); //use regular expression to get cookie to be a name array
return unescape(arr[2]); //
return ”;

3. delete cookie

<script type="text/javascript" language="JavaScript">
function deleteCookie(name){
            var date=new Date();
            document.cookie=name+"=v; expire="+date.toGMTString();  }  

the more details of cookie usage could be referenced by


jQuery summary (I)

First of all, jQuery is a JavaScript library, and all reference and relative API document can be found at Official website. So for the explanation of “jQuery”, that website’s definition on the first page can be referenced: It is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

1. Why bother jQuery

a. Overcoming browser differences
Different browsers handle DOM manipulation, transparency effects, and animation in different ways,using a JavaScript library allows you to completely bypass most of those challenges, giving you access to an API that deals directly with the effects or result you actually want to accomplish. Revoking jQuery allows you to integrate functionality without wondering whether or not it will work in a particular browser.

b. Unobtrusive JavaScript
Another reason to use a JavaScript library is that all libraries allow you to include JavaScript in your pages unobtrusively, thus keeping your behavior layer (the JavaScript) separate from the content and presentation layers (the XHTML and CSS).

c. Accomplishing complex tasks with ease
jQuery is a very powerful library and may the most mature and stable Javascript library comparing with others. It can manipulate any element or set of elements on a web page with just one line of code, which you may compose/test your own function to achieve the same effects for at least hours(Maybe I am just writing slow….).

2. Pre knowledge for jQuery

a. Understand CSS concepts especially the selector usage
jQuery often utilizes CSS-based syntax to manipulate DOM elements. When I first develop function by jQuery, googled quite a few code snippet, but really confused the way jQuery used to reference an element. As in javascript, normally you just use document.getElementByID or similar etc. But after being familiar with the CSS selector syntax, I can feel the power and charming of the jQuery way. Read the following article you can get a basic idea of how CSS selector works 30 CSS Selector you need to know and the way to use it in jQuery Find the element you want

b. JavaScript concept

As jQuery is an essential a JavaScript library, so understand JavaScript concept, syntax is a must. Most of us already understand OO concepts which is the core mechanic of JS, but JS has some specialties comparing the other OO language. Some important concept you may need to consider in your development
@ It is a parsed language and not a compiled one;

@ Anonymous function. In C#, delegation has the similar feature. you will noticed that jQuery use anonymous function to bind a function to the element event, such as button click, mouse hover etc.

@ JS doesn’t support a notion class. This may be changed in JS 2.0? But JS function can behave similarly as class. See the car object creation below.

 * @constructor
function Car(make, model, year, color) {
  this.Make = make;
  this.Model = model;
  this.Year = year;
  this.Color = color;
  this.FullName = this.Year + " " +
  "<b>" + this.Make + "</b> " +
var mySUV = new Car("Toyota", "4Runner SR5",2001, "Thundercloud");
document.write ("I drive a " + mySUV.FullName);

@ JSON. JSON can let you build javascript object, when jQuery call ajax, if the back webservice methods’ parameter needs an object, then you need build JSON object (can deliver XML but JSON object is much more convenient than XML parser) then “stringify” it and parse to the web service. (This will explain more in my “jQuery AJAX” article). JSON details can be referenced to JSON Tutorial. Before use JSON, you need download the .js file and reference. JSON official website

3. Finally jQuery itself

Before getting started with any jQuery development, you’ll first have to download the latest version of the jQuery library from the official website and include it in your pages:

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

After that, I think the best jQuery tutorial are already on Internet, so just put some links. An overview video tutorial Video tutorial, tutorial for beginner, Official tutorial (Official normally is boring…) 51 best tutorial Another absolute beginner tutorial

4. Performance.

jQuery is so powerful, however if you abused to use jQuery, the web page loading or switching could be slow and sometime the animation will be stuck. So use jQuery only when it really needs and also consider the following tips to improve the performance as well, all of them are very straight forward.
10 tips to improve jQuery performance

JavaScript Field validater

The following is a validate which use Javascript regularexpress to implement. The part to revoke javascript function is “ onchange=”regcheckTimeSeconds(this);

The regular express patter could find at the site:

Front page code.

<asp:TemplateField HeaderText="From">
	<FooterStyle HorizontalAlign="Right" />
	<HeaderStyle HorizontalAlign="Left" Width="120px" />
	<ItemStyle CssClass="" HorizontalAlign="Left" Width="120px" VerticalAlign="Top" />
		<asp:Button ID="btnTime1" Text="T" runat="server" OnClick="gdEdit_TimeSet" />
		<asp:Button ID="btnTime2" Text="-" runat="server" OnClick="gdEdit_TimeSet" />
		<asp:Button ID="btnTime3" Text="+" runat="server" OnClick="gdEdit_TimeSet" />
		<br />
		<asp:TextBox ID="txtTimeFrom" Width="80px" Text='<%# Eval("TimeStart", "{0:T}").ToString.ToLower %>' onchange="regcheckTimeSeconds(this);" AutoPostBack="false" TabIndex="20" runat="server" />


JavaScript code

	function regcheckTimeSeconds(txtbox) {
        var s = txtbox.value
        //var reg = new RegExp("^((([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?))$");
        //var reg = new RegExp("^((([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?))$");

        // var reg = new RegExp("^([1-9]|1[0-2]|0[1-9]){1}(:[0-5][0-9](\:[0-5][0-9]\s?[aApP][mM])){1}$");
        var reg = new RegExp("^(1[0-2]|[1-9]):[0-5][0-9]:[0-5][0-9][ ]?[aApP][mM]$");

	    if ((/^\s*$/).test(s)) {
            if (String(s).search(reg) == -1) {
       = "red";
                alert("The time format is incorrect.\r\n\r\nThe correct format is:\r\nHH:MM:SS am/pm\r\n\r\nFor example:\r\n11:41:55 pm");
            } else {
       = "black";


Real refresh the web page

When an iframe/html/aspx page been refreshed,  the browser won’t refresh completely instead it may just refresh from cache as the url is exactly the same as before. To achieve the real refresh, can added a “Date.Now.Millisecond” into query string, and this will change the url every time and let browser do a fresh real refresh.

        Dim cs As ClientScriptManager = p.ClientScript()
        Dim t As Type = sendertype
        Dim s As String = "window.parent.document.getElementById('LeftFrame').src='dlist1.aspx?" & "time=" & Date.Now.Millisecond & "&did=1';" & _
                          "window.parent.document.getElementById('RightFrame').src='" + urlstr + "'; "
        'Dim s As String = "'dlist1.aspx?debateid=1', 'LeftFrame'); "
        cs.RegisterStartupScript(t, "D frame refresh", s, True)

Javascript count down timer

The following count down will use a javascript function to calculate what content needs to show on the div and using setInterval(CountDown, 1000); to trigger the display per seconds.

1. basic countdown by seconds.

step 1. create a .js file, put the following function and variant.

var maxtime = 35

function CountDown() {
    if (document.getElementById("divCountDown").style.display=='none')
        document.getElementById("divCountDown").style.display = 'block'

    if (maxtime >= 1) {
        seconds = maxtime - 1;
        msg = "Time left:  " + seconds + "  seconds";
        document.getElementById("divCountDown").innerHTML = msg;
    else {
        alert("time is over");
        document.getElementById("divCountDown").style.display = 'none'

 function triggerCountDown()
    timer = setInterval(CountDown, 1000);

step 2. hookup the code with a asp button in aspx page.

<div id="divCountDown" style="display: none; color: red;"></div>

2. hours count down

 minutes = Math.floor(maxtime/60);
 seconds = Math.floor(maxtime%60);
 msg = "Time left: "+minutes+"  minutes"+seconds+" seconds";
 if(maxtime == 5*60) alert('there are 5 minutes left');
 alert("time is over");
timer = setInterval("CountDown()",1000);
<div id="timer" style="color: red;"></div>

3. Fancy countdown

display like the following.


<div id="javascript_countdown_time"></div>
<pre>var javascript_countdown = function () {
	var time_left = 10; //number of seconds for countdown
	var output_element_id = 'javascript_countdown_time';
	var keep_counting = 1;
	var no_time_left_message = 'No time left for JavaScript countdown!';

	function countdown() {
		if(time_left < 2) {
			keep_counting = 0;

		time_left = time_left - 1;

	function add_leading_zero(n) {
		if(n.toString().length < 2) {
			return '0' + n;
		} else {
			return n;

	function format_output() {
		var hours, minutes, seconds;
		seconds = time_left % 60;
		minutes = Math.floor(time_left / 60) % 60;
		hours = Math.floor(time_left / 3600);

		seconds = add_leading_zero( seconds );
		minutes = add_leading_zero( minutes );
		hours = add_leading_zero( hours );

		return hours + ':' + minutes + ':' + seconds;

	function show_time_left() {
		document.getElementById(output_element_id).innerHTML = format_output();//time_left;

	function no_time_left() {
		document.getElementById(output_element_id).innerHTML = no_time_left_message;

	return {
		count: function () {
		timer: function () {

			if(keep_counting) {
				setTimeout("javascript_countdown.timer();", 1000);
			} else {
		//Kristian Messer requested recalculation of time that is left
		setTimeLeft: function (t) {
			time_left = t;
			if(keep_counting == 0) {
		init: function (t, element_id) {
			time_left = t;
			output_element_id = element_id;

//time to countdown in seconds, and element ID
javascript_countdown.init(3673, 'javascript_countdown_time');

Prohibit using F5 refresh

Add the following JavaScript to the header part or under <asp:Content > tag.

		function checkKeyCode(evt) {
			var evt = (evt) ? evt : ((event) ? event : null);
			var node = ( ? : ((evt.srcElement) ? evt.srcElement : null);
			if (event.keyCode == 116) {
			evt.keyCode = 0;
			return false
		document.onkeydown = checkKeyCode;

OnClientClick and OnClick

First scenario: An asp button with no onclick event but only the onclientclick event. This event revoke a javascript function to start a timer and display the count down on the Div layer. Each time the button clicked, the whole web page gets refreshed, obviously even no OnClick event, it still post back.
“return false;” should applied after revoke onclientclick.

OnClientClick="setInterval('CountDown()',1000);return false;"
OnClientClick="return confirm('This OQP Session will be saved as verified. \n Are you sure?');"

Second scenario: In a web page submit process, the validation needs to be done before the submit, if failed to validate, then submit should not be triggered. However, no matter return false or ture after revoke the validation code, form still get submitted.

<asp:Button ID="SubmitBtn" runat="server" Text="submit"
OnClientClick="return txtcheck();"
OnClick="SubmitBtn_Click" />

function txtcheck()
   //username cannot be null
   var UserName = document.form1.txtUserName.value;
   if (UserName == ""){
             alert("Login cannot be null! ");
             return false;