表单信息的localStorage

用户在填写表单时,有可能会出现浏览器崩溃或不小心刷新的情况。如果表单填写的内容较多,势必给用户带来不便。因此,将表单信息及时的存入localStorage,在出现崩溃之后,表单已填写的内容就不会消失了。

1.使用sisyphus.js插件

     应用该插件后,只需添加一行代码即可:
$( "#your_from_id" ).sisyphus();
当我们希望点击提交之后,消除localStorage的数据时,只需要添加:
 window.localStorage.clear();

    2.出于对用户安全性的考虑,对于存如本地的用户信息,应当进行适当的处理,这里就需要使用另外一个插件lzwCopress.js
    通过此插件,可以将表单数据先进行打包,然后再存入localStorage,取数据时先进行解压,在输出数据:
//打包json后再localstorage
var myStorege = function(){

    //对localstorage的json数据进行打包
    var lzwCompress = window.lzwCompress;
    //取值
    var localMsg;
    if(window.localStorage.formHistory){
        //localMsg=JSON.parse(window.localStorage.formHistory);
        // And to decompress it
        var localMsg = lzwCompress.unpack(JSON.parse(window.localStorage.formHistory));
    }

    if(localMsg && localMsg.length>=1){
        var realIndex=0;
        for(var i=0;i<$('#regform input').length;i++){
                $($('#regform input')[i]).val(localMsg[realIndex].text)
                realIndex++;
        }
        for(var i=0;i<$('#regform textarea').length;i++){
            $($('#regform textarea')[i]).val(localMsg[realIndex+1].textarea)
            //console.log(realIndex)
            realIndex++;
        }
        for(var i=0;i<$('#regform select').length;i++){
                $($('#regform select')[i]).val(localMsg[realIndex+1].select!=""?localMsg[realIndex+1].select:"2人")
                //console.log(realIndex)
                realIndex++;
        }
    }
    //赋值
    $('#regform input,#regform textarea,#regform select').bind('input',function () {
        //console.log("here")
        var history = [];
        window.localStorage.formHistory = '';
        for (var i = 0; i < $('#regform input').length; i++) {
            history.push({"text": $($('#regform input')[i]).val()})
        }
        for (var i = 0; i < $('#regform textarea').length; i++) {
            history.push({"textarea": $($('#regform textarea')[i]).val()})
        }
        for (var i = 0; i < $('#regform select').length; i++) {
            history.push({"select": $($('#regform select')[i]).val()})
        }
        // To compress anything from within JS
        var compressed = lzwCompress.pack(history);
        window.localStorage.formHistory = JSON.stringify(compressed)
    
    })
}
注意,绑定的input事件可以监听表单的内容改变,从而进行数据存储。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值