Question

I have a form with several rows. I would like to calculate the totals for each row. i.e. cost * unit price and put the result in the total input. Here is the script I tried:

<script>
$(document).ready(function(){
    var input;
    $('#p1').keyup(calculate('#p1'));
    $('#p2').keyup(calculate('#p2'));
});
function calculate(input)
{
    $(input + 'Total').val($(input).val() * $(input + 'cost').val());

}
</script>
Was it helpful?

Solution

At least one problem is that the .keyup() method expects a function. The way you use calculate in your example, you invoke the function immediately when adding the event.

To avoid this, you could do something like this:

$('#p1').keyup(function () { calculate('#p1') });

Another option would be to have the calculate function return a function reference:

function calculate(input)
{
    return function () {
        $(input + 'Total').val($(input).val() * $(input + 'cost').val());
    }
}

You could then add the event-handler as you do today:

$('#p1').keyup(calculate('#p1'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top