Search code examples
javascriptundefinedcounterinputbox

Javascript: Getting undefined on input box that takes a range from 0 to 10


I have two buttons (+ and -) and an input box with a value of 10. The input must take a value from 0 to 10 only and I can't figure out why I'm getting undefined after I reach either 0 or 10 on the input box. I tried using parseInt for the values. But perhaps I'm not doing it on the right place. Would appreciate the help.

var fighterScore1 = document.getElementById("fighterScore1");
fighterScore1.value  = 10;
var fighter1Inc = document.getElementById("fighter1Inc");
var valor = 10;

	fighter1Inc.onclick = function (valor) {
		fighterScore1.value = increaseValue(valor);
	};
	fighter1Dec.onclick = function (valor) {
		fighterScore1.value = decreaseValue(valor.value);
	};
  function decreaseValue() {
		if (valor <= 0 ) {

	    } else {
	    valor--;
	    	return valor;
	    }
	};
	function increaseValue() {
		if (valor >= 10 ) {
	    	valor = 10;
	    } else {
	    valor++;
	    	valor = valor;
	    	return valor;
	    }
	    
	};
<div id="rwid1">
			<button id="fighter1Inc">+</button>
			<input type="text" id="fighterScore1" maxlength="10" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
			<button id="fighter1Dec">-</button>
		</div><!--/rwid-->


Solution

  • The problem is that you're only returning inside the condition that it is less than 10 or greater than 0. If you don't return in one condition,there is no return value so you end up assigning undefined to a variable. Here is a fixed JSFiddle. You have to return outside the if statements, and valor.value doesn't exist.

    var fighterScore1 = document.getElementById("fighterScore1");
    fighterScore1.value  = 10;
    var fighter1Inc = document.getElementById("fighter1Inc");
    var valor = 10;
    
    fighter1Inc.onclick = function (valor) {
    	fighterScore1.value = increaseValue();
    };
    
    fighter1Dec.onclick = function (valor) {
    	fighterScore1.value = decreaseValue();
    };
    
    function decreaseValue() {
    	if (valor <= 0 ) {
            valor = 0;
    	} else {
    	    valor--;
    	}
    	return valor;
    };
    
    function increaseValue() {
    	if (valor >= 10 ) {
    	    valor = 10;
    	} else {
    	    valor++;
    	}
        return valor;
    };
    <div id="rwid1">
    	<button id="fighter1Inc">+</button>
    	<input type="text" id="fighterScore1" maxlength="10" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
    	<button id="fighter1Dec">-</button>
    </div><!--/rwid-->

    A note: you pass arguments into a function that takes none (JS accepts a varying number of arguments, even if you don't specify). Either you remove the call with arguments, or you use an argument and pass it in, using the argument in place of valor.