Ramin
Ramin

Reputation: 55

Sum form value and show it

i want to sum value that selected in ckeckbox on the html form by javascript See the following example :

<form>
<input type="checkbox" id="digit_1">
<input type="checkbox" id="digit_2">
<input type="checkbox" id="digit_3">
<input type="checkbox" id="digit_4">

<div id="result"></div>
<input type="submit">
</form>

so i want to give the checkbox values ​​in javascript like the following figure:

digit_1 = 10
digit_2 = 5
digit_3 = 1
digit_4 = 20

And for example when "digit_1" and "digit_3" selected , it show sum of it (11) in the result div And when "digit_3" has Removed = 11 - 1 = 10 show the 10 number in the div

Upvotes: 2

Views: 171

Answers (2)

Andr&#233; Snede
Andr&#233; Snede

Reputation: 10045

You could do the following

<form>
    <input type="checkbox" class="summable" id="digit_1" data-value="10">
    <input type="checkbox" class="summable" id="digit_2" data-value="5">
    <input type="checkbox" class="summable" id="digit_3" data-value="1">
    <input type="checkbox" class="summable" id="digit_4" data-value="20">
    <div id="result"></div>
</form>

And JS:

function updateSum(){
    var sum = 0;
    $('form input.summable:checked').each(function(){
        sum+=parseInt($(this).attr('data-value'),10);
    });
    $('#result').html('Sum: ' + sum);
}

updateSum();

$(document).on('change', 'input.summable', updateSum);

And a JSFiddle to show it off: http://jsfiddle.net/cxh8s/

Upvotes: 1

wizulus
wizulus

Reputation: 6333

First, you can store the values of the checkboxes on the checkboxes them selves:

<form>
    <input type="checkbox" id="digit_1" value="10">
    <input type="checkbox" id="digit_2" value="5">
    <input type="checkbox" id="digit_3" value="1">
    <input type="checkbox" id="digit_4" value="20">

    <div id="result"></div>
    <input type="submit">
</form>

Then in your script, you can loop through each one and sum up the values:

var value;
for (var i = 1; i <= 4; i++) {
    var checkbox = document.getElementById("digit_" + i);
    if (checkbox.checked) {
        value += +checkbox.value;
    }
}
result.innerText = value;

Your answer will display in the <div>.

Upvotes: 2

Related Questions