Mehdi Brillaud
Mehdi Brillaud

Reputation: 1866

Calculation on keypress event (or number only in keyup event)

I try to calculate a discount and allowing numbers only in the discount field. When I use the keyup event, the calculation is right but I still can type any characters, if I use the keypress event, the restriction on characters works but the calculation does not work anymore (the first input is not recorded).

Here is a codepen of my code : http://codepen.io/mbrillaud/pen/jEzBGy?editors=101

$(document).ready(function(){
    var $discount = $('#discount'),
        $price = $('#price'),
        $newPrice = $('#new-price');


    $discount.on('keypress', function(e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)){
            return false;
        }
    $newPrice.val(
        Math.round(
            ($price.val() - (($discount.val() / 100) * $price.val()))* 100) / 100
        );
    });
});

I used an answer from stackoverflow to check the numbers.

Thanks by advance for your help

Upvotes: 1

Views: 5963

Answers (3)

user5308956
user5308956

Reputation:

Here is a simple example that works great!

Html code :

Qty:<input type='text' name='qty' id='qty' value='' /> <br/>
Price:<input type='text' name='price' id='price' /> <br/>
Total:<input type='text' name='total' id='total' /> <br/>

And script :

$('#qty, #price').on('input', function () {
    var qty = parseInt($('#qty').val());
    var price = parseFloat($('#price').val());
    $('#total').val((qty * price ? qty * price : 0).toFixed(2));
});

Test here : DEMO

Upvotes: 0

haim770
haim770

Reputation: 49095

You can combine both keypress and keyup events to achieve this. Use keypress to prevent unwanted characters, and keyup for the actual calculation.

You'll also have to use e.stopImmediatePropagation() to make sure keyup won't proceed with the calculation even when an invalid character entered:

$discount.on('keypress', function(e)
{
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)){
        e.stopImmediatePropagation();
        return false;
    }
}
.on('keyup change', function(e)
{
    $newPrice.val(Math.round(($price.val() - (this.value / 100) * $price.val()))* 100) / 100);
});

I took the liberty to hook for a change event as well, so the total will get updated when you delete characters (using backspace or delete key) as well.

See updated Codepen

Upvotes: 2

void
void

Reputation: 36703

Use both keyup keypress like this.

$discount.on('keyup keypress', function(e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)){
            e.stopImmediatePropagation();
            return false;
        }

But i guess in your code you are also disabling delete, left, right, backspace which a user won't like i guess.

Here is a function which is more user friendly and allows number, left, right, backspace, delete.

function validateQty(event) {
    var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46
 || event.keyCode == 37 || event.keyCode == 39) {
    return true;
}
else if ( key < 48 || key > 57 ) {
    return false;
}
else return true;
};

And to use it, do,

$discount.on('keyup keypress', function(e) {
        e.stopImmediatePropagation();
        return validateQty(e);
        }

Upvotes: 2

Related Questions