웹 개발/🌐 JavaScript
쿠키를 이용하여 아이디저장기능 구현
이재원
2023. 5. 25. 15:26
1. 로그인
<input type="text" id="userId">
<input type="checkbox" id="idSaveCheck">아이디 저장하기
2. 아이디 저장
$(document).ready(function(){
var key = getCookie("key");
$("#userId").val(key);
if($("#userId").val() != ""){
$("#idSaveCheck").attr("checked", true);
}
$("#idSaveCheck").change(function(){
if($("#idSaveCheck").is(":checked")){
setCookie("key", $("#userId").val(), 7); //7일간 보관
}else{
deleteCookie("key");
}
});
$("#userId").keyup(function(){
if($("#idSaveCheck").is(":checked")){
setCookie("key", $("#userId").val(), 7); //7일간 보관
}
});
});
function setCookie(cookieName, value, exdays){
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var cookieValue = escape(value) + ((exdays==null) ? "" : "; expires=" + exdate.toGMTString());
document.cookie = cookieName + "=" + cookieValue;
}
function deleteCookie(cookieName){
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() - 1);
document.cookie = cookieName + "= " + "; expires=" + expireDate.toGMTString();
}
function getCookie(cookieName) {
cookieName = cookieName + '=';
var cookieData = document.cookie;
var start = cookieData.indexOf(cookieName);
var cookieValue = '';
if(start != -1){
start += cookieName.length;
var end = cookieData.indexOf(';', start);
if(end == -1)end = cookieData.length;
cookieValue = cookieData.substring(start, end);
}
return unescape(cookieValue);
}
웹사이트를 다시 접속하면 이렇게 아이디가 자동으로 입력되어진다
반응형