user3108268
user3108268

Reputation: 1083

Increment number in a div on click

I have this solution with <form> and <input> elements.

function incrementValue()
{
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}
<form>
   <input type="text" id="number" value="0"/>
   <input type="button" onclick="incrementValue()" value="Increment Value" />
</form>

But how do I achieve same effect by clicking an <a></a> button and incrementing value inside a <div></div>?

Upvotes: 1

Views: 1156

Answers (2)

luek baja
luek baja

Reputation: 1674

Do you mean like this?

const a = document.getElementById("a"),
  div = document.getElementById("div");
  
a.addEventListener("click", event => {
  //this is just to prevent redirects when you click the link
  event.preventDefault();
  
  //gets the number in div
  const num = parseInt(div.innerHTML);
  
  //increments the number
  div.innerHTML = num + 1;
});
<a id="a" href="">Anchor Tag</a>
<div id="div">0</div>

Upvotes: 1

buzatto
buzatto

Reputation: 10382

I would suggest to use a button rather than anchor which makes more sense as a html tag for that. You would manipulate property innerText for this:

function incrementValue()
{
    var value = parseInt(document.getElementById('number').innerText, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').innerText = value;
}
<div id="number"/>0</div>
<button onclick="incrementValue()" />Increment Value</button>

Upvotes: 1

Related Questions