Limit the amount of items in an Input by default total value

Asked

Viewed 104 times

1

I have a variable with that value:

var total = 10;

And two input:

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

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

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: http://jsfiddle.net/6to9Ltr5/

  • 1

    Sergio, that’s right! I’ve been waiting for you. Now, I just need one more thing: You made the second input zero when a total was exceeded, okay, you could make, instead of zeroing, the consequent input get what’s left of the subtraction between the two? EXAMPLE PUT : 5 and 6 Then I should put 5 and 5 to the user.

  • @Lollipop Yes, that’s simple, just use this.value = this.value - (sum - total);. Thus: http://jsfiddle.net/6to9Ltr5/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.