Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate with jquery in dynamically added rows and build a total of a column

I have a (HTML) form with dynamically added fields on demand. If you enter something in a field, you get a row.

In the end it calculates a grand total.

HTML

<form id="myForm">Factor:
    <input type="text" name="factor" value="6" />
    <fieldset id="cloneset">
        <input type="text" name="qty[1]" />
        <input type="text" name="product[1]" onkeyup="if (this.value.length > 2 && treated[this.name] != 1){ addOne(); treated[this.name] = '1'; }"
        />
        <input class="cost" type="text" name="amount[1]" onkeyup="calculateSum();" />
    </fieldset>
    <input id="total" type="text" name="total">
</form>

jQuery

treated = new Object();
inputNumber = 1;

function addOne() {
    inputNumber++;
    $('#cloneset').append('<div><input type="text" name="qty[' + inputNumber + ']" /> <input type="text" name="product[' + inputNumber + ']" onkeyup="if (this.value.length > 2 && treated[this.name] != 1){ addOne(); treated[this.name] = \'1\'; }" /> <input class="cost" type="text" name="amount[' + inputNumber + ']" onkeyup="calculateSum();" /></div>');
}

function calculateSum() {

    var sum = 0;
    //iterate through each textboxes and add the values
    $(".cost").each(function () {
        //add only if the value is number
        if (!isNaN(this.value) && this.value.length != 0) {
            sum += parseFloat(this.value);
        }
    });
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $("#total").val(sum.toFixed(2));
}

I have a working demo in a fiddle

Now I'd like to enter – let's say – hours, that get multiplicated with a (fixed) rate.

Lokking for a best practice to do this.

like image 967
zarquon Avatar asked Dec 06 '25 08:12

zarquon


1 Answers

HTML

<form id="myForm">Rate:
<input type="text" name="factor" value="6" id="rate" class="rate" />
<table id="cloneset">
    <tr>
        <td>
            <input type="text" name="qty[1]" onkeyup="calculateRow();" class="qty" />
        </td>
        <td>
            <input type="text" name="product[1]" onkeyup="if (this.value.length > 2 && treated[this.name] != 1){ addOne(); treated[this.name] = '1'; }" />
        </td>
        <td>
            <input class="cost" type="text" name="amount[1]" onkeyup="calculateSum();" />
        </td>
    </tr>
</table>
<input id="total" type="text" name="total">

jQuery

treated = new Object();
inputNumber = 1;

function addOne() {
    inputNumber++;
    $('#cloneset').append('<tr><td><input type="text" name="qty[' + inputNumber + ']" onkeyup="calculateRow();" class="qty" /></td><td><input type="text" name="product[' + inputNumber + ']" onkeyup="if (this.value.length > 2 && treated[this.name] != 1){ addOne(); treated[this.name] = \'1\'; }" /></td><td><input class="cost" type="text" name="amount[' + inputNumber + ']" onkeyup="calculateSum();" /></td></tr>');
}

function calculateSum() {

    var sum = 0;
    //iterate through each textboxes and add the values
    $(".cost").each(function () {
        //add only if the value is number
        if (!isNaN(this.value) && this.value.length != 0) {
            sum += parseFloat(this.value);
        }
    });
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $("#total").val(sum.toFixed(2));
}

function calculateRow() {

    $('.qty, .rate').change(function () {
        var cost = 0;
        var $row = $(this).closest("tr");
        var qty = parseFloat($row.find('.qty').val());
        var rate = parseFloat($("#rate").val())
        cost = qty * rate;
        //        alert($("#rate").val());

        if (isNaN(cost)) {
            $row.find('.cost').val("Nix is");
        } else {
            $row.find('.cost').val(cost);
        }
        calculateSum();
    })
}

Working solution in a fiddle

This might be in a horrible programming style. Suggestions for improvements welcome.

like image 175
zarquon Avatar answered Dec 10 '25 15:12

zarquon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!