John Evans Solachuk
John Evans Solachuk

Reputation: 2085

jQuery : How to prevent insertion into input field after sum of multiple input fields has been reached?

I have successfully come out with this code after searching through Google and stackoverflow however, there is only one problem.

Let's say the amount_available is 125. By right, I should only be able to input numbers with total sum of < 125 but I can put in numbers one-digit more like 1111 or 3 digit number bigger than 125 like 999. How do I correct this? Other than that, it works fine.

Below are my codes :


JQuery

var amount_available = $('input[name=amount_available]').val();
$(".multiple_spec").on('keydown','input[name*=quantity]',function(e){
    var total_quantity=0;
    $(this).parents('[class*=multiple]').find('input[name*=quantity]').each(function(){
        var val = parseFloat($(this).val());
        if(isNaN(val))val = 0;
        total_quantity=(val+total_quantity);
    });
    if(total_quantity>amount_available){
        // Allow: backspace, delete, tab, escape, and enter
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
            // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        e.preventDefault();
    }
});

HTML

<input type="text" name="amount_available"/>
<div class="multiple_spec">
    <div class="some_class">
        <input type="text" name="quantity1"/>
        <input type="text" name="quantity2"/>
        <input type="text" name="quantity3"/>
    </div>
</div
<div class="multiple_price">
    <div class="random_class">
        <input type="text" name="quantity4"/>
        <input type="text" name="quantity5"/>
        <input type="text" name="quantity6"/>
    </div>
</div

Upvotes: 0

Views: 117

Answers (1)

Johan
Johan

Reputation: 35194

You need to do your validation in a keyup event rather than keydown, since you won't have access to the most recent value there.

How about something like this:

var $quantityInputs = $(".multiple_spec input[name*=quantity]");

$quantityInputs.on('keyup',function(e){

    var amount_available = +$('input.amount_available').val(),
        // Extract values from quantity input fields:
        total_quantity = $quantityInputs.map(function(i, el){ 
            return +$(el).val() || 0;
        // Add them all together:
        }).get().reduce(function(prev, curr){
            return prev + curr;
        }, 0);

    if(total_quantity > amount_available){
        console.log('total quantity exceeds available amount - do something');
        $(this).val(function(index,value){
            return value.substr(0,value.length-1);
        });
    }
});

http://jsfiddle.net/rwrLt4cm/6/

Upvotes: 1

Related Questions