Sprunkas
Sprunkas

Reputation: 433

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!

Upvotes: 0

Views: 1018

Answers (3)

shramee
shramee

Reputation: 5099

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()) || 0;  // If a string is entered, use 0 instead.
    });

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

});

Upvotes: 0

wot
wot

Reputation: 845

This updates the totals.

$(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));

    // Get all the totals from each row and convert them to 
    // an array of floats. Then sum them together with reduce
    var totalPrice = $('.total').map(function (index, el) {
        return parseFloat($(el).val()) || 0;
    }).get().reduce(function (a,b) { return a + b }, 0)

    // Update the total field with the calculated totals
    $('#totals').val(totalPrice)
});

https://jsfiddle.net/xqy6qafk/2/

Upvotes: 1

misha130
misha130

Reputation: 5746

Remove change so it'll activate on keyup

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

Upvotes: 1

Related Questions