0

I've created a simple site where visitors can vote on a particular subject. It consists of a single question and three choices:

<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>

I'm using the Session Amplify package to store form values in localStorage as well as the DB, which is working perfectly.

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

After the visitor has logged their vote they're shown the global results of the vote as a bar cart. They can only see the results after they vote, though.

What I need to do is remember the user's vote when they visit the site again so they can bypass the vote and go straight to the results, all without forcing them to create an account or log in. I'm already storing their response in localStorage that are accessible by simply running SessionAmplify.get('vote').

How can I use these stored values to pre-populate the form and show them the results?

4

1 回答 1

0
    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 代码,因为我不能在fiddle中使用它。这只是为了证明 localStorage 有效。

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

于 2015-01-24T20:04:09.423 回答