Basic JavaScript Question:
Download Job Interview Questions and Answers PDF
How to getting values from cookies to set widgets?
Answer:
function getCookieData(labelName) {
//from Danny Goodman
var labelLen = labelName.length;
// read cookie property only once for speed
var cookieData = document.cookie;
var cLen = cookieData.length;
var i = 0;
var cEnd;
while (i < cLen) {
var j = i + labelLen;
if (cookieData.substring(i,j) == labelName) {
cEnd = cookieData.indexOf(";",j);
if (cEnd == -1) {
cEnd = cookieData.length;
}
return unescape(cookieData.substring(j+1, cEnd));
}
i++;
}
return "";
}
//init() is called from the body tag onload function.
function init() {
setValueFromCookie("brand");
setValueFromCookie("market");
setValueFromCookie("measure");
}
function setValueFromCookie(widget) {
if( getCookieData(widget) != "") {
document.getElementById(widget).value = getCookieData(widget);
}
}
//if you name your cookies the widget ID, you can use the following helper function
function setCookie(widget) {
document.cookie = widget + "=" +
escape(document.getElementById(widget).value) + getExpirationString();
}
//from Danny Goodman
var labelLen = labelName.length;
// read cookie property only once for speed
var cookieData = document.cookie;
var cLen = cookieData.length;
var i = 0;
var cEnd;
while (i < cLen) {
var j = i + labelLen;
if (cookieData.substring(i,j) == labelName) {
cEnd = cookieData.indexOf(";",j);
if (cEnd == -1) {
cEnd = cookieData.length;
}
return unescape(cookieData.substring(j+1, cEnd));
}
i++;
}
return "";
}
//init() is called from the body tag onload function.
function init() {
setValueFromCookie("brand");
setValueFromCookie("market");
setValueFromCookie("measure");
}
function setValueFromCookie(widget) {
if( getCookieData(widget) != "") {
document.getElementById(widget).value = getCookieData(widget);
}
}
//if you name your cookies the widget ID, you can use the following helper function
function setCookie(widget) {
document.cookie = widget + "=" +
escape(document.getElementById(widget).value) + getExpirationString();
}
Download JavaScript Interview Questions And Answers
PDF
Previous Question | Next Question |
How to setting a cookie with the contents of a textbox? | How to Handle Event Handlers? |