2011年10月12日 星期三

利用javascript把form的內容儲存在cookie中

有時候user會需要不斷重填某份表單,但這份表單中有些內容是不需重填的,這時候就會希望把不需重填的部份存到cookie,並且在user每次進入網頁時自動讀取,以減少user使用上的麻煩。
我們可以用jquery達到這個目標:
function remember( selector ){
    $(selector).each(
        function(){
            //if this item has been cookied, restore it
            var name = $(this).attr('name');
            if( $.cookie( name ) ){
                    $(this).val( $.cookie(name) );
            }
            //assign a change function to the item to cookie it
            $(this).change(
                function(){
                        $.cookie(name, $(this).val(), { path: '/', expires: 6 });
                }
            );
        }
    );
}
$(document).ready(
    function(){
        if($.cookie('host')=='ptt2')
            $("#host_ptt2").attr("checked","checked");
        else
            $("#host_ptt").attr("checked","checked");
        remember('[name=ptt_ID]');
        remember('[name=aid]');
        remember('[name=board]');
    }
);
本文未完成,有待補完

沒有留言:

張貼留言