简体   繁体   中英

Calculate form inputs onChange

I have a dynamic form that is being generated based on what the user adds to the cart.

For example, the form will looks something like this,

    <!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test Form</title>
</head>
<body>
    <form action="" name="cart" id="cart">
    <input type="text" name="sku1">
    <input type="text" name="sku2">
    <input type="text" name="sku3">
    <input type="text" name="sku4">
    <input type="text" name="sku5">

    <div class="sum" id="sum"> Total: {SUM SHOULD SHOW UP HERE)</div>
    <button name="submit">Send</button>
    </form>
</body>
</html>

But those input fields are generated automatically and may be more or less than 5 fields.

How to calculate those input SUM value and output to SUM div without page refresh?

JavaScript/jQuery?

$('button[name="submit"]').click(function () {
    var sum = 0;
    $('#cart input[name^="sku"]').each(function () {
        var val = isNaN(+this.value) ? 0 : +this.value; 
        sum += val;
    });
    $('#sum').text(sum);
});


Or

 var inp = $('#cart input[name^="sku"]'); inp.change(function () { var sum = 0; inp.each(function () { var val = isNaN(+this.value) ? 0 : +this.value; sum += val; }); $('#sum').text(sum); }); 

Attribute Starts With Selector [name^="value"]

.change()

isNaN()

You can use the onsubmit attribute of the form to do whatever you want to before the form gets submitted. You can change action attribute also. You can also preventDefault as said here-

jQuery on submit preventDefault() does not works

You can give the elements a class, amountForTotal , and use a function to calc the total, which you can add to a button, or onchange event of an input.

function calcTotal( $elements ){
    var total = 0;
    $elements.each(function(){
        // if the input has no value, add 0, if it has, add the value
        total+= this.value.length===0 ? 0 : parseInt(this.value); 
    })
    return total; // return the total
}

$elements = $('.amountForTotal'); // select them
// Bind an event to recalc the total
$elements.on('keyup', function(){
    alert( calcTotal($elements) );
});

In this code I provided the selector as input. This is luxery, not needed, you can add that selector in the function, but this way it can be used more flexible. You can use the [name^=*] selector here, but its slower than a class, which you might notice in large documents.

Also, In my code I check if it has to no value to prevent errors. You can expand this to test if the input is actualy a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM