Search code examples
javascripthtmlbuttonvar

Prevent var from going negative


I have a button with a var that start with a 0 and when you click a another button it increases to 1. But if you click the second button first, the var goes negative. The button is disabled at the beginning, but when it increases to 1 the button should be enabled.

When the page is loaded the button disabled, but when the var goes to 1 the button is still disabled. I tried: if(var == 0){document.getElementById("button1").disabled = true; return false;}


Solution

  • You can do something like in below snippet :

    You can use any tag instead of input like div span h1 ... which ever you wish and style according to need .
    This thing you will need to change will be change .value to .innerHTML everywhere like this(1 example) :
    var units = document.getElementsByClassName("unitsMain")[0].innerHTML

    function decreaseUnits() {
      var units = document.getElementsByClassName("unitsMain")[0].value
      if (units > 0) {
        units--;
        document.getElementsByClassName("unitsMain")[0].value = units;
      }
    }
    
    function increaseUnits() {
      var units = document.getElementsByClassName("unitsMain")[0].value
      units++;
      document.getElementsByClassName("unitsMain")[0].value = units;
    }
    <button class="decOrderUnits" onclick="decreaseUnits()"><i class="fa fa-minus"></i>-</button>
    <input class="unitsMain" value="0" maxlength="3">
    <button class="incOrderUnits" onclick="increaseUnits()"><i class="fa fa-plus"></i>+</button>