Start at 0 and keep adding by 10

1480 views javascript
8

This script is designed when you press the button it will show 0 and when you press the button again it will show 10 and keep adding by 10 every time you press the

button for example 0,10,20,30,40,etc... how can I do this I tried many methods but I can not generate something like this.

document.querySelector('#add-by-ten').addEventListener('click',addByTen);

function addByTen(){
/*???*/
document.querySelector('#result').innerHTML = ?;
}
<button id='add-by-ten'>Add by ten</button>
<p id='result'></p>

answered question

try to search similar problems before positing.

4 Answers

4

var resultElement = document.getElementById('result')

function addByTen(){
   var value = parseInt(resultElement.innerHTML, 10);

   if (!Number.isInteger(value)) {
      resultElement.innerHTML = 0;
   } else {
      resultElement.innerHTML = value + 10;
   }
}

document.querySelector('#add-by-ten').addEventListener('click',addByTen);

posted this
3

using a var counter = 0; in the outer scope, then add 10 when you click the button.

document.querySelector('#add-by-ten').addEventListener('click',addByTen);
var counter = 0;

window.onload  = function init(){
  document.querySelector('#result').innerHTML = counter;
}
function addByTen(){
   counter+=10;
   document.querySelector('#result').innerHTML = counter;
}
<button id='add-by-ten'>Add by ten</button>
<p id='result'></p>

posted this
6

Set a global variable, let number = 0;

Set inner.Text to that variable.

Then have your plusTen function () {number = number +10}

posted this
1

You've almost got it!

There's four steps to achieving this:

  1. Use your quest selector to retrieve the current value from your label.
  2. Cast the retrieved innerHTML as a number.
  3. Increment this number by 10.
  4. Set your new number as the innerHTML of your query selector.

Here's a working copy of the code:

document.querySelector('#add-by-ten').addEventListener('click',addByTen);

function addByTen(){
  var currentValue = document.querySelector('#result');
  currentValue.innerHTML = Number(currentValue.innerHTML) + 10;
}
<button id='add-by-ten'>Add by ten</button>
<p id='result'>0</p>

There are a few ways to achieve what you're doing, which could involve storing a global variable to keep your count; or by using DOM manipulation like your original attempt.

posted this

Have an answer?

JD

Please login first before posting an answer.