jQueryでフォームの内容をCookieに保存する

JavascriptでCookieを扱うのはどうも敷居が若干お高めですが、jQueryプラグインのjquery.cookie.jsがあると、誰でも簡単にCookieマスターになれます!
jquery.cookie.js Download
公式jQueryからはなぜかうまくダウンロードできなかったので、こちらからどうぞ。
jquery.cookie.js使い方 How To Use It.
Cookieの書き込み
Create session cookie:
$.cookie(‘the_cookie’, ‘the_value’);
$.cookie(‘the_cookie’, ‘the_value’);
有効期限付きのCookie
以下は7日間限定のCookieの作成方法。
Create expiring cookie, 7 days from then:
$.cookie(‘the_cookie’, ‘the_value’, { expires: 7 });
$.cookie(‘the_cookie’, ‘the_value’, { expires: 7 });
ページを限定するCookie
特定のページでのみCookieを有効にする場合
Create expiring cookie, valid across entire page:
$.cookie(‘the_cookie’, ‘the_value’, { expires: 7, path: ‘/’ });
$.cookie(‘the_cookie’, ‘the_value’, { expires: 7, path: ‘/’ });
Cookieの読み込み
Read cookie:
$.cookie(‘the_cookie’); // => ‘the_value’
$.cookie(‘not_existing’); // => null
$.cookie(‘the_cookie’); // => ‘the_value’
$.cookie(‘not_existing’); // => null
フォームに記入した内容をCookieに保存する
最後にITかあさんの作ったCookieサンプル。
フォームに入力した内容をCookieに保存します。
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script src="jquery.cookie.js"></script>
<script type="text/javascript">
$(function(){
//読み込んだクッキーをフォームのvalue値として代入
$('#name').val($.cookie("name"));
$('#age').val($.cookie("age"));
$('#email').val($.cookie("email"));
$('#tel').val($.cookie("tel"));
$('#pr').val($.cookie("pr"));
//submitを押したら、クッキーを保存
$("#submit").click(function(){
$.cookie("name",$('#name').attr('value'));
$.cookie("age",$('#age').attr('value'));
$.cookie("email",$('#email').attr('value'));
$.cookie("email_re",$('#email_re').attr('value'));
$.cookie("tel",$('#tel').attr('value'));
$.cookie("pr",$('#pr').attr('value'));
location.href="index.html"
})
})
</script>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<th>Name</th>
<td><input type="text" name="name" id="name" value=""></td>
</tr>
<tr>
<th>Age</th>
<td><input type="text" name="age" id="age" value=""></td>
</tr>
<tr>
<th>E-mail</th>
<td><input type="text" name="email" id="email" value=""></td>
</tr>
<tr>
<th>Tel</th>
<td><input type="text" name="tel" id="tel" size="38" value="" /></td>
</tr>
<tr>
<th>Text</th>
<td><textarea name="pr" rows="4" cols="30" id="pr"></textarea></td>
</tr>
<tr>
<th></th>
<td><input type="submit" value="決定" id="submit"></td>
</tr>
</table>
今日のまとめ
一度読みこんだCookieは$(‘#name’).val($.cookie(“name”));といった具合に簡単に呼び出せますね。ピュアJavascriptでCookie操作はなかなか敷居が高いので今回のプラグインはWEBデザイナーの方でも無理なくCookie操作を行うのに最適ですね