代码之家  ›  专栏  ›  技术社区  ›  Brandon Durham

在不登录的情况下记住用户的表单输入

  •  0
  • Brandon Durham  · 技术社区  · 11 年前

    我创建了一个简单的网站,访问者可以在这里对特定主题进行投票。它由一个问题和三个选项组成:

    <template name="addVote">
        <div class="form-row choices">
            <label><input type="radio" name="vote" value="Yes"><i></i><span>Yes</span></label>
            <label><input type="radio" name="vote" value="No"><i></i><span>No</span></label>
            <label><input type="radio" name="vote" value="Undecided"><i></i><span>I’m Undecided</span></label>
        </div>
        <div class="form-row">
            <button class="button-submit">Submit and view results</button>
        </div>
    </template>
    

    我正在使用 Session Amplify 包将表单值存储在localStorage和DB中,这是一个完美的工作环境。

    var vote = $('[name="vote"]:checked').val();
    Meteor.call("addVote", vote, function(error, voteId) {
        SessionAmplify.set('vote', vote);
    });
    

    访客登录投票后,他们会将投票的全局结果显示为一个购物车。不过,他们只能在投票后才能看到结果。

    我需要做的是记住用户再次访问网站时的投票,这样他们就可以绕过投票直接进入结果,而无需强制他们创建帐户或登录。我已经将他们的响应存储在localStorage中,只需运行 SessionAmplify.get('vote') .

    如何使用这些存储的值预填充表单并向其显示结果?

    1 回复  |  直到 11 年前
        1
  •  0
  •   Mouser    11 年前
        if (localStorage.vote) {
            //user has already cast a vote, reflect this
            document.querySelector(".form-row").querySelector("input[value='"+localStorage.vote+"']").setAttribute("checked", true);
            //disable the submit
            document.querySelector(".button-submit").setAttribute("disabled", true);
        } 
    
        function setLocalStorageVote()
        {
             //call when user has cast the vote.
             localStorage.vote = document.querySelector(".form-row").querySelector("input[type='radio']:checked").value;
        }
    
    
     document.querySelector(".button-submit").onclick = setLocalStorageVote; //using onclick here just for demonstrating purposes. Use addEventListener in production code!
    
    <template name="addVote">
        <div class="form-row choices">
            <label><input type="radio" name="vote" value="Yes"><i></i><span>Yes</span></label>
            <label><input type="radio" name="vote" value="No"><i></i><span>No</span></label>
            <label><input type="radio" name="vote" value="Undecided"><i></i><span>I’m Undecided</span></label>
        </div>
        <div class="form-row">
            <button class="button-submit">Submit and view results</button>
        </div>
    </template>
    

    应该这样做。只需存储 布尔型 并绕过代码以获得基于localStorage.vote值的结果。 localStorage 在投票的客户上无限期设置。请注意,我已经删除了Meteor代码,因为我不能在 不停摆弄 。这只是为了演示localStorage的工作原理。

    http://jsfiddle.net/8fzur0h9/1/

    推荐文章