Search code examples
jqueryhtmleventsicheck

iCheck sum and subtract values


Using the library of iCheck I have a basic html:

<form>
    <input type="radio" name="pks" value="1">
    <input type="radio" name="pks" value="2">
    <input type="radio" name="pks" value="3">
    <hr>
    <input type="checkbox" name="op1" value="10">
    <input type="checkbox" name="op2" value="20">
    <input type="checkbox" name="op3" value="30">
    <input type="checkbox" name="op4" value="40">
</form>

So then I have my jQuery:

$('input[name="pks"]').on('ifChecked', function(e) {
    var $pkss = $(this).val();
    $('input[type="checkbox"]').on('ifChecked', function(ev) {
        var $ops = $(this).val();
        sum = parseFloat($pkss) + parseFloat($ops);
        // alert(sum);
        $('#tt').text(sum)
    });
    $('input[type="checkbox"]').on('ifUnchecked', function(ev) {
        var $ops = $(this).val();
        sum = parseFloat($pkss) - parseFloat($ops);
        // alert(sum);
        $('#tt').text(sum)
    });

});

What I'm trying to accomplish is very simple without the use of iCheck, but since I'm learning this library and there is no documentation for this kind of operation using iCheck(I couldn't find any) I need to "sum" the values from the radio input to the checkbox
if radio input 1 is selected then the value is 1, then check if a checkbox has been checked if so, then sum that value to the radio button that has been checked:
like: 1radio + 10checkbox = 11, so 11 is my result but what if:
2radio + 10checkbox + 40checkbox then = 52... correct?, but if the user uncheck one of the checkboxes then subtract that value... with the code above kid of, sort of working... I manage to sum one radio and one checkbox but if I select a different radio button it doesn't do nothing until I select another checkbox but it ignores the first checkbox and when I deselect a checkbox it gives me the wrong result... I can't make it work using iCheck...


Solution

  • The easiest way to achieve this is to have a single function which runs on change of both the radio and checkbox inputs. This function will then total the values of all selected elements, instead of adding/removing the current value from a stored total.

    Try this:

    $(':radio, :checkbox').change(updateTotal);
    
    function updateTotal() {
        var total = 0;
        $(':radio:checked, :checkbox:checked').each(function () {
            total += parseInt(this.value);
        });
        console.log(total);
    }
    

    Example fiddle