TomDev
TomDev

Reputation: 287

How to keep updating value of a variable by clicking on a button in JavaScript after it was entered in INPUT first?

I'm a rookie JS programmer making first steps into programming, so I appreciate your help to help me learn it.

I have created a function that adds 5 to a value entered by the user in INPUT. The result is displayed in . It works perfectly. After clicking the button the result shows up. However, I want to use the same button to keep adding another 5 to the output value without entering a new value in the INPUT.

I've tried: -declaring the undefined value (let sum; )outside the function to make the variable global but it didn't work.

I was thinking about:

let sum;
let sum2;

function adder5() {
  let userNumber = Number(document.querySelector("#yourNumber").value);
  sum = userNumber + 5;
  document.querySelector("#output").textContent = sum;
}

document.querySelector("#btn").addEventListener("click", adder5);

function adderContinue(sum) {
  document.querySelector("#btn").addEventListener("click", function () {
    sum2 = sum + 5;
  });
  document.querySelector("#output").textContent = sum2;
}
<input id="yourNumber" type="number" />
<button id="btn">Calculate</button>
<p id="output"></p>

I appreciate your help. Any hint will do because I'm stuck. BTW I realize that variable SUM changes into SUM2 after the first click event, but the code should work at least once.

Upvotes: 2

Views: 3063

Answers (2)

Shreevardhan
Shreevardhan

Reputation: 12641

You could use the input field's event to update the cached value and update it on button click.

const input = document.getElementById('input'),
  button = document.getElementById('button'),
  output = document.getElementById('output');
let value = input.valueAsNumber;

input.oninput = function () {
  value = this.valueAsNumber;
};

button.onclick = function () {
  value += 5;
  output.textContent = isNaN(value) ? '' : value;
};
<input type="number" id="input" />
<button id="button">Calculate</button>
<p id="output"></p>

Upvotes: 1

Mohib Arshi
Mohib Arshi

Reputation: 830

  • You may create a variable to store old user input and check if it is equivalent to the new user input or not.
  • If it is equal then only add 5 to the sum
  • Else add the user input with 5
let sum = 0;
let oldUserInput = 0;

function adder5() {
  let currentUserInput = Number(document.querySelector("#yourNumber").value);
  
  if(currentUserInput === oldUserInput){
    sum = sum + 5;
  } else {
    sum = currentUserInput + 5;
    // Update the oldUserInput to the current
    oldUserInput = currentUserInput;
  }
  document.querySelector("#output").textContent = sum;
}

document.querySelector("#btn").addEventListener("click", adder5);

Upvotes: 0

Related Questions