sanchit arora
sanchit arora

Reputation: 11

simple buttons for adding and subtracting of numbers

I am trying to create two simple buttons for adding and subtracting of numbers. Here's the code

function add() {
  document.getElementById("output").innerHTML = Number(document.getElementById("output").innerHTML) + 1;
}


function sub() {
  document.getElementById("output").innerHTML = Number(document.getElementById("output").innerHTML) - 1;

  if (Number(document.getElementById("output").innerHTML) <= 0) {
    document.getElementById("swe").style.visibility = "hidden"
  } else if (Number(document.getElementById("output").innerHTML) >= 1) {
    document.getElementById("swe").style.visibility = "visible"
  }
}
<button value="sub" onclick="sub()" id="swe">-</button>
<span id="output">0</span>
<button value="add" onclick="add()" id="sqr">+</button>

So, the button is working fine for adding the numbers but it isn't getting displayed back again when the innerHTML is >=1? What could be the reason for the same?

Upvotes: 0

Views: 72

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Your check to see if the output is less than 1 only occurs in the sub function, but the sub function is only called by the subtract button, which is hidden the first time the output gets less than 1 - so, it'll never reappear.

Carry out the check in both functions instead:

const output = document.getElementById("output");
function check() {
  const outputNum = Number(output.textContent);
  document.getElementById("swe").style.visibility =
    outputNum <= 0 ?
    'hidden' :
    'visible';
}

function add() {
  output.textContent = Number(output.textContent) + 1;
  check();
}

function sub() {
  output.textContent = Number(output.textContent) - 1;
  check();
}
<button value="sub" onclick="sub()" id="swe">-</button>
<span id="output">0</span>
<button value="add" onclick="add()" id="sqr">+</button>

(also note that unless you're deliberately inserting or checking HTML markup, you should check/set the textContent instead of the .innerHTML)

Upvotes: 2

Related Questions