Click here to Skip to main content
15,915,810 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So what I'm trying to do is that I have an arrow (up and down) when the arrow up is clicked, there is variable that counts how many times we clicked and the result is seen in a paragraph
HTML
<p id="count">0</p>

However, everytime I try to add another let's say div with the same up and down arrow (same class) and same paragraph id count when I click the up arrow on the new div, the result is outputted on my very first paragraph.

What I have tried:

JavaScript
var counter=0;
function mycount() {


document.getElementById("count").innerHTML = ++counter;
}

function myminus(){
      document.getElementById("count").innerHTML = --counter;
	  if(counter<0){
	  counter=0
	  document.getElementById("count").innerHTML = 0;
    }

}


I have an up arrow with an onclick="mycount()" and down arrow with an onclick="myminus()" I know my problem which is the getElementById("count") I want to be able to add an up and down arrow with a new paragraph and having the output be on the new paragraph. It doesn't really seem efficient if I copy and paste my javascript code and changing the getElementById("putIDhere")
Posted
Updated 29-Apr-18 22:52pm
v2

1 solution

If you have two divs both with the id of "count" then how do you expect document.getElementById("count") to know which div you want to get? ids have to unique on a page. If you need multiple instances of your arrows then you'll need a unique id for each. The simplest way is probably to add a number to the id so the first div will be "count0", then "count1" etc. Every time you add a new instance increment the number.

Next you need to change the js to accept this number

function myminus(id){
      document.getElementById("count" + id).innerHTML = --counter;
	  if(counter<0){
	  counter=0
	  document.getElementById("count" + id).innerHTML = 0;
    }

}


Any code that calls myminus needs to know its own id to pass into the function.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900