0

when I click the like button the increment value incremented but it not working corresponding as the button incremented. How will do it?

index.html

<div class="row">
    <div class="col-md-4">
         <i class="fa fa-thumbs-up" onclick="count(this, '{{datas.id}}', '{{datas.user_id}}')" id="odd">
          </i>
          <span id="add"></span>
    </div>  
    <div class="col-md-4"></div>
    <div class="col-md-4 text-right">{{datas.post_date}}</div>
</div>

inbox.js

var counter=0;
function count(id, data, out)
{   
    counter++;
    var one = id.closest('.card-body');
    one.querySelector('#add').innerHTML = counter;    
}

Like button increment but not start from 1 it starts from previous number

2
  • 1
    How is this related to Python? Commented Oct 8, 2020 at 17:00
  • 1
    Websites like this are usually connected to a database, where the data are being stored. So, when someone likes a post, it increments and saves the value in the database. Then it just refreshes the value (reads from database after change). This is not a JavaScript thing, unless you use server side JS like Node.js. Otherwise, you can save the data to a file locally and manage it like that. Commented Oct 8, 2020 at 17:04

1 Answer 1

1

You can not rely on global counter. You need to have each item specific counter. One of the approach you can take is to add data attribute on node itselft and update on each click, for example:

function count(id, data, out) {
  const counter = parseInt(this.getAttribute("data-counter") || 0) + 1; // read current counter
  this.setAttribute("data-counter", counter); // update counter

  var one = id.closest('.card-body');
  one.querySelector('#add').innerHTML = counter;
}
<div class="row">
  <div class="col-md-4">
    <i class="fa fa-thumbs-up" data-counter="0" onclick="count(this, '{{datas.id}}', '{{datas.user_id}}')" id="odd"></i>
    <span id="add"></span>
  </div>
  <div class="col-md-4"></div>
  <div class="col-md-4 text-right">{{datas.post_date}}</div>
</div>

Sign up to request clarification or add additional context in comments.

4 Comments

I got error like "Uncaught TypeError: this.getAttribute is not a function".
@KumarR can you check if this is not null? It should be element. Try replacing this in method with id and see if that works.
Thank you for your timely helping. Now it's working i could not change the id value instead of this element. Any other possible way without using the set and get Attribute method.
You can create a dictionary of key value and in the event handler read and update correct value in the dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.