Search code examples
jqueryhtmlinputpercentagejquery-calculation

jQuery counting percentage - shows "undefined"


My script should counts values in table but it can't replace '%' char and shows 'undefined'. I tried some solution but no luck.

I made a fiddle: fiddle

    $('table .ilosc, table .cena_netto .stawka_vat').on('keyup paste change', function() {
        $('table tr').each(function() {
            var ilosc = $(this).find('input.ilosc').val();
            var cena_netto = $(this).find('input.cena_netto').val();
            var wartosc_netto = (ilosc * cena_netto);
            $(this).find('input.wartosc_netto').val(wartosc_netto);
            var stawka_vat = $(this).find('input.stawka_vat').val().replace('%', '');
            var  kwota_vat = ( wartosc_netto * (stawka_vat / 100) );
            $(this).find('input.kwota_vat').val(kwota_vat);
            var wartosc_brutto = (wartosc_netto + kwota_vat);
            $(this).find('input.wartosc_brutto').val(wartosc_brutto);
        }); //END .each
    return false;
}); // END change

It works fine until line: $(this).find('input.wartosc_netto').val(wartosc_netto);


Solution

  • I think I found it... You do an each on all <tr> rows. The first row is a header. So it will not find any values. Replace that row with <thead> and then the undefined error doesnt occur. When an error like this happens, the rest of the script will stop.

    Even better is to give the <tr> a class and then loop through the classes.

    Mind you, make a fall back, when no value is found BEFORE you do the replace