teh kc teh kc - 5 months ago 26
Javascript Question

How to cancel the vote, if someone click on upvote/downvote button 2 times

I made a upvote/downvote button here
. Now i want it to cancel the vote, if someone click on the upvote/downvote button 2 times. Example: 1st click = vote +1/-1, 2nd click = vote -1/+1 (depending, if he click on upvote or downvote)

HTML:

<center><button class="buttonup" id="plus" style="vertical-align:middle" > <span>Upvote </span> </button> <span id="count">0</span>
<button class="buttondw" id="minus" style="vertical-align:middle"><span>Downvote </span> </button></center>


<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>


Javascript

$(document).ready(function() {
function checkIfUserVoted() {
return true ? localStorage.getItem("voted") === "true" : false
}

var counter = 0;
if(localStorage.getItem("count") == null)
$("#count").text(0);
else {
counter = localStorage.getItem("count");
$("#count").text(counter);
}


$("#plus").click(function(){

if (checkIfUserVoted()) {

} else {
localStorage.setItem("voted", "true");
counter++;
$("#count").text(counter);
localStorage.setItem("count", counter);
}

});

$("#minus").click(function(){

if (checkIfUserVoted()) {

} else {
localStorage.setItem("voted", "true");
counter--;
$("#count").text(counter);
localStorage.setItem("count", counter);
}
});
});

Prs Prs
Answer

You can do this only saving one data to localstorage current number of votes. Try running this code..

var counter = 0, // Try change this what ever you want
  votePlus = counter + 1,
  voteMinus = counter - 1;

function checkIfUserVoted() {
  return localStorage.getItem("voted");
}
if (!localStorage.getItem("voted")) {
  localStorage.setItem("voted", counter);
  $("#count").text(counter);
}
$("#plus").click(function() {
  var vote = checkIfUserVoted() != votePlus ? votePlus : counter;
  localStorage.setItem("voted", vote);
  $("#count").text(vote);
});
$("#minus").on('click', function() {
  var vote = checkIfUserVoted() != voteMinus ? voteMinus : counter;
  localStorage.setItem("voted", vote);
  $("#count").text(vote);
});

See this working fiddle