Jigna Jain Jigna Jain - 2 months ago 7
jQuery Question

Using checkbox to decide which input boxes value to sum

I am trying to write some Javascript/jQuery to sum the value entered in multiple text boxes.

Each input box has a checkbox associated with it, and based on that checkbox the value will be added to the total. For example, if the user selects

Activity fees
and
Transport fees
they should add up, if he selects
Misc fees
that will also add up, and if he then unchecks
Misc fees
, that value should be subtracted again.



function optionalfee() {
var total = 0;
var fee = document.getElementsById('optional1');
for (var i = 0; i < fee.length; ++i) {
if (optional1.checked == true)
document.getElementById('optional').value = fee;
total += parseFloat(fee.value);
}
} else {
total -= parseFloat(fee.value);
}
//alert(total);
document.getElementById('toptional').value = total;
}

Include Activity fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="afees"><br><br>
Include Transport fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="tfees"><br><br>
Include Misc fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="mfees"><br><br>
Include Olympiad fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="ofees"><br><br>
Optional fees total <input type="number" id="toptional" name="toptional" class="toptional" readonly>




Answer

Javascript to sum the value entered in multiple number inputs every time an element checkbox or input change:

var total = document.getElementById('toptional'),
    checkboxs = Array.prototype.slice.call(document.getElementsByClassName('checkbox')),
    inputs = Array.prototype.slice.call(document.getElementsByClassName('fee')),
    all = checkboxs.concat(inputs),
    getTotalFee = function() {
        var totalFee = 0;
        for (var i = 0, len = checkboxs.length; i < len; i++) {
            checkboxs[i].checked && (totalFee += +inputs[i].value);
        }
        total.value = totalFee;
    };

// Attach event change to all classes "checkboxs" and "fee", to getTotalFee
for (var i = 0, len = all.length; i < len; i++) {
    all[i].addEventListener('change', getTotalFee, false);
}
Include Activity fees: 
<input type="checkbox" class="checkbox" />
<input type="number" class="fee" name="afees"><br>

Include Transport fees: 
<input type="checkbox" class="checkbox" />
<input type="number" class="fee" name="tfees"><br>

Include Misc fees: 
<input type="checkbox" class="checkbox" />
<input type="number" class="fee" name="mfees"><br>

Include Olympiad fees: 
<input type="checkbox" class="checkbox" />
<input type="number" class="fee" name="ofees"><br>

<br><br><hr>

<strong>Optional fees total:</strong>
<input type="number" id="toptional" name="toptional" class="toptional" readonly>

Comments