PCM
PCM

Reputation: 47

Can someone help me with my button functions?

When I press the minus button on the left, I would like for the number on the left side of the equals sign (in this case "7") to count down one number for each button click until it reaches zero.

I have html, css, and js files working together. I put them into one file and cut out any unnecessary code for the purpose of posting here. My problem is (I think) in the function leftMinusButton() and how it communicates with the html.

function leftMinusButton() {
  var i = document.getElementById("leftnum");

  if (i > 0) {
    i--;
  }
}
body {
  font-family: arial, "times new roman";
  background: lightblue;
  color: black;
  text-align: center;
}

.leftminus {
  position: absolute;
  top: 60px;
  left: 30px;
  width: 50px;
  height: 50px;
  font-size: 40px;
}

.variable {
  position: absolute;
  top: 120px;
  left: 115px;
  font-size: 40px;
}

.plus {
  position: absolute;
  top: 120px;
  left: 175px;
  font-size: 40px;
}

.leftnum {
  position: absolute;
  top: 120px;
  left: 240px;
  font-size: 40px;
}

.equals {
  position: absolute;
  top: 120px;
  left: 300px;
  font-size: 40px;
}

.rightnum {
  position: absolute;
  top: 120px;
  left: 350px;
  font-size: 40px;
}
<div id="workspace">
  <div class="variable" id="variable">x</div>
  <div class="plus" id="plus">+</div>
  <div class="leftnum" id="leftnum">7</div>
  <div class="equals" id="equals">=</div>
  <div class="rightnum" id="rightnum">19</div>
</div>

<div id="plusminus">
  <button type="button" class="leftminus" id="leftminus" onclick="leftMinusButton()">-</button>
</div>

Upvotes: 0

Views: 48

Answers (2)

jordiburgos
jordiburgos

Reputation: 6302

You would need to set the new value of i back to the element "leftnum". Also, for getting the value of the element "leftnum" you need to access the innerHTML property.

var i = document.getElementById("leftnum");
var value = parseInt(i.innerHTML);
if (value  > 0) {
    value--;
}
i.innerHTML = value;

Upvotes: 2

andy mccullough
andy mccullough

Reputation: 9591

document.getElementById() will only get you the DOM node, you then need to get the value from it (innerHTML), do whatever you need to do, then set the result. May I suggest you have a look at innerHTML - https://www.w3schools.com/jsref/prop_html_innerhtml.asp for how to get the value, and how it can be set

Upvotes: 1

Related Questions