Mendark
Mendark

Reputation: 23

Increment and Decrement Javascript not working

i made a JavaScript function to increment and decrement a number in the like button, here is the function

var val = 0; 
var negative = false;
$('.i-t').click(function(){
val = val + ((negative) ? -1 : 1); 
negative = (negative) ? false : true;
$("#myval").text(val);
});

This function works great on the first click but clicking the second time it doesn't remove the value, is something wrong with the function? here is the button

 <button id="myvals" class="myvals">
 <i class="myvals" id="i-t"></i> 
 <span class="myvals" id="voteScore">123</span></button>

i want to change the 123 to 124 if liked and 122 if disliked and it doesn't works, i'm sorry i had to prepare the question better from the beginning

Upvotes: 1

Views: 755

Answers (3)

Mukesh Kalgude
Mukesh Kalgude

Reputation: 4844

Try this:

var val = 0;
var negative = false;
$('.i-t').click(function() {
    val = parseInt($("#voteScore").val()) + ((negative) ? -1 : 1);
    negative = (negative) ? false : true;
    $("#myval").text(val);
});

Upvotes: 0

RobG
RobG

Reputation: 147343

You need two buttons, one for up and one for down, or you could use one button and a checkbox for up or down, but I think two buttons is simpler.

When reading values from DOM elements, they're generally strings so if numbers are required, particularly for addition, don't forget to convert the value to a number before doing arithmetic.

So the buttons and code can be something like:

function vote(n) {
  // Get the element to update
  var el = document.getElementById('votes');

  // Convert the text content to Number, then add value
  el.textContent = Number(el.textContent) + n;
}
Votes: <span id="votes">123</span>
<button onclick="vote(1)">up vote</button>
<button onclick="vote(-1)">down vote</button>

Of course this is just a demo, adapt it however you wish.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

From your comments and update, what you want to do is to increase/decrease the vote count based on whether you have already clicked or not.

In that case, instead of using a variable, you can store the state using a class to support multiple vote button if you need like

$('button.vote').click(function () {
    var $btn = $(this).toggleClass('voted');
    $(this).find("span.score").text(function (i, val) {
        return +val + ($btn.hasClass('voted') ? 1 : -1);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="myvals vote"> <i class="myvals" id="i-t">here</i><span class="myvals score">123</span></button>

Upvotes: 1

Related Questions