Limit quantity of items in an Input by default total value

1

I have a variable with this value:

var total = 10;

And two input:

<input type="text" name="foto-1">
<input type="text" name="foto-2">
  

I need the client to be hindered by a value in which the sum of each input is greater than the total of 10 , DYNAMICALLY .

    
asked by anonymous 10.06.2015 / 21:53

1 answer

1

Suggestion:

var total = 10;
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener('keyup', checkInputs);
}

function checkInputs(e) {
    var sum = [].map.call(inputs, function (i) { // mapear cada input ao seu valor com Type: number
        return parseFloat(i.value) || 0;
    }).reduce(function (a, b) { // somar todos os inputs
        return a + b;
    });
    console.log(sum);
    if (sum > total ) { // verificar
        alert('valor grande demais!');
        this.value = 0;
    }
}

jsFiddle: link

    
10.06.2015 / 22:01