I have textarea and input tags, I want that when I enter, after each character, the information in the fields is saved in a coockie with a name consistent with the name (preferably) or id, and after clicking on the button, everything is erased (from the cookie). Help please implement this in javascript
- If it is impossible to put a cookie somewhere else, but so that it can be extracted using PHP - Vitaly Zaslavsky
|
1 answer
function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function checkCookie() { var username=getCookie("username"); if (username!=null && username!="") { alert("Welcome again " + username); } else { username=prompt("Please enter your name:",""); if (username!=null && username!="") { setCookie("username",username,365); } } } var element = document.getElementById('myTextArea'); element.onkeyup = function(){ var val = element.value; setCookie("user1",val,17);//Вместо user1 вставьте любой идентификатор, уникальный для данного пользователя и текстового поля. Как вы его добудете - уже не мои проблемы. =) Кука живет в данном случае 17 дней. } - And you can for more, please. What does each of the functions do in this case? - Vitaly Zaslavsky
- setCookie - writes data to the cookie. getCookie - gets data from a cookie. checkCookie is one example of the use of cookies. 4 lines below - an example of use for your case. - knes
|