How to limit the increase of a value depending on one already established in an input?

0

In this code I want to limit the increase depending on the numbers set in input

var contador = 0;
var c = document.getElementById("lol");

function incrementar() {
  if (contador == c) {
    alert('Maximo permitido alcanzado:' + 'lol');
  } else {
    document.caca.muchacaca.value = contador++;
  }
}

function decrementar() {
  if (contador == 0) {
    alert('Minimo permitido alcanzado: 0');
  } else {
    document.caca.muchacaca.value = contador--;
  }
}
<form name="caca">
  <input id="lol" type="text" value="5" readonly="readonly">

  <br>

  <input type="button" onClick="incrementar()" value="aumentar">
  <input type="button" onClick="decrementar()" value="disminuir">
  <label> 
    <input name="muchacaca" type="text" readonly="readonly"> 
    </label>
</form>
    
asked by Ben Escobar 15.03.2018 в 21:36
source

1 answer

1

The problem is that c is DOMElement with id="lol" , when what you really need is the value of that element.

Solution:

To obtain the numeric value saved in input you can use parseInt ( integer ) or parseFloat ( with decimals )

Example

var contador = 0;
// AQUI obtenemos el value como número entero
var c = parseInt(document.getElementById("lol").value, 10);

function incrementar() {
  if (contador == c) {
    alert('Maximo permitido alcanzado:' + 'lol');
  } else {
    document.caca.muchacaca.value = contador++;
  }
}

function decrementar() {
  if (contador == 0) {
    alert('Minimo permitido alcanzado: 0');
  } else {
    document.caca.muchacaca.value = contador--;
  }
}
<form name="caca">
  <input id="lol" type="text" value="5" readonly="readonly">

  <br>

  <input type="button" onClick="incrementar()" value="aumentar">
  <input type="button" onClick="decrementar()" value="disminuir">
  <label> 
    <input name="muchacaca" type="text" readonly="readonly"> 
    </label>
</form>
    
answered by 15.03.2018 / 21:45
source