Sprunkas Sprunkas - 5 months ago 10
jQuery Question

How to update input value without clicking on input field?

So I have problem that my input value is updated only when I clicked on input field ("Total" input field, below "Suma" ("Kiekis" * "Kaina" = "Suma") column and which is readonly), but I want to automatically update "totals" field (Which is at the bottom near "Bendra suma").

JS code:

$(document).on('keyup change', '.quantity, .price', function() {
var row = $(this).closest('tr').get(0);
var rowPrice = $(row).find('.price').val();
var rowQuantity = $(row).find('.quantity').val();

$(row).find('.total').val((rowPrice * rowQuantity).toFixed(2));

$('.total').blur(function () {
var sum = 0;

$('.total').each(function() {
sum += parseFloat($(this).val());
});

$('#totals').val((sum).toFixed(2));
});

});


You can test how it works in JSFiddle:

https://jsfiddle.net/xqy6qafk/

Thanks in advance for help!

Answer

You don't need to put the code in blur event handler...

Put it in keyup/change event handler section...

Remove 8th line

$(document).on('keyup', '.quantity, .price', function() {

and second last line...

});

So you have something that looks like this...

$(document).on('keyup change', '.quantity, .price', function() {
    var row = $(this).closest('tr').get(0);
    var rowPrice = $(row).find('.price').val();
    var rowQuantity = $(row).find('.quantity').val();

    $(row).find('.total').val((rowPrice * rowQuantity).toFixed(2));

    var sum = 0;

    $('.total').each(function() {
        sum += parseFloat($(this).val());
    });

    $('#totals').val((sum).toFixed(2));

});
Comments