0

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
John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67
  • The class names in your HTML should not be prefixed with dots (`.`). – Robby Cornelissen Aug 22 '14 at 09:12
  • "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" Could you explain this. I didn understand? – wallop Aug 22 '14 at 09:19
  • @Wishy This code allows me to input numbers like 1111 or 999 but these numbers are not acceptable because they are `>125`. I need to correct this. – John Evans Solachuk Aug 22 '14 at 09:25

1 Answers1

1

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/

Johan
  • 35,120
  • 54
  • 178
  • 293
  • It works, but how do I prevent numbers from being added? e.preventDefault() doesn't seem to do it. – John Evans Solachuk Aug 22 '14 at 09:37
  • @Mark No, preventing the default behavior won't help you here. But you can remove the last entry if it's invalid. Please see my update – Johan Aug 22 '14 at 10:47
  • http://stackoverflow.com/questions/8545376/limit-number-of-characters-allowed-in-form-input-text-field – mplungjan Aug 22 '14 at 10:55
  • @mplungjan Simply limiting the length is not enough in this case. – Johan Aug 22 '14 at 10:56
  • No, but it will stop the 1111 – mplungjan Aug 22 '14 at 11:20
  • +1 but I was looking for something more like preventing the digit that makes the sum greater than `amount_available` from being added in the first place. Also, when I press a certain number without releasing, it still accepts the number and only -1 after I release it. basically, I need something that validates the value before it is added into the textbox. – John Evans Solachuk Aug 23 '14 at 01:27
  • @Mark I'm afraid you won't know what the last character is until the keyup event is triggered. Regarding not releasing a button, you can handle that in the keypress event. – Johan Aug 23 '14 at 12:40