Search code examples
jqueryincrement

Increment Value of Span only once


So I have an ajax which goes something like this:

$('.clike').each(function(){
$(this).on("click", function(e) {

    e.preventDefault();

    var commentLike = $(this).data('id');

    $.ajax({
        type: "POST",
        url: "//link",
        dataType: "JSON",
        cache: false,
        statusCode: {
            200: function () {
                console.log('worked! '+commentLike);

                var newValue = parseInt($(".clikebadge"+commentLike).text(), 10) + 1;

                $(".clikebadge"+commentLike).text(newValue);
            }
        },

    });
});
});

So my question here is with this part.

var newValue = parseInt($(".clikebadge"+commentLike).text(), 10) + 1;

$(".clikebadge"+commentLike).text(newValue);

So every time I click the like button, it gives a status 200. But I do not want to keep incrementing the value of the span. It does work. I mean it does increment. But I don't want it to keep on incrementing. I want it to increment only once and stop. I want to increment only once. Right now it keeps on going. How can I do this with JQuery.

I know there is a JQuery once.('click') but I don't see how I could use that in this context.


Solution

  • You can do this by saving the state. (In the example in data-incremented)

    A better way to do this is to return true or false by your JSON if the like has been placed by the user already.

    $('.clike').each(function() {
      $(this).on("click", function(e) {
    
        e.preventDefault();
    
        var commentLike = $(this).data('id');
    
        $.ajax({
          type: "GET",
          url: "https://jsonplaceholder.typicode.com/posts/1",
          dataType: "JSON",
          cache: false,
          statusCode: {
            200: function() {
              console.log('worked! ' + commentLike);
              
              var $badge = $(".clikebadge[data-for-id=" + commentLike + "]");
              if ($badge.data('incremented') !== 1) {
                console.log( 'incrementing' );
    
                var newValue = parseInt($badge.text(), 10) + 1;
                $badge.text(newValue);
    
                // save increment
                $badge.data('incremented', 1);
              }
            }
          },
    
        });
      });
    });
    .clikebadge {
      background-color: #7C7;
      padding: 5px 10px;
      border-radius: 10px;
      color: #FFF;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="button" class="clike" data-id="99" value="Click me!" />
    <span class="clikebadge" data-for-id="99">1</span>