0

I have a form that has input checkboxes like the ones in the example. The js code extracts the number from the checked input values and outputs them one next to eachother. How to I edit the code so that when you check a second input checkbox the output is the sum of the numbers?

This is the PHP form:

<input type="checkbox" onchange="toggleCheckbox(this)" value="abc 1 def" name="1">
<input type="checkbox" onchange="toggleCheckbox(this)" value="abc 2 def" name="2">
<input type="checkbox" onchange="toggleCheckbox(this)" value="abc 3 def" name="3">

The JavaScript i use:

<script type="text/javascript"> 
    function toggleCheckbox(element){
        if (element.checked){
        var number = element.value.replace ( /[^\d.]/g, '' );
        document.getElementById("test").innerHTML += " " + number;
        }
} 
</script>

The HTML field:

<p id="test"></p>
2
  • 1
    use a variable to hold the sum .. place it outside the scope of your function and add new value to it and print that instead of the number .. Commented Aug 27, 2014 at 13:38
  • Well give the value just the number, and then in the check if just add em up.. Commented Aug 27, 2014 at 13:38

2 Answers 2

1

You could store the accomulated value in a global variable, E.g.:

var sum = 0;

function toggleCheckbox(element){
        var number = element.value.replace ( /[^\d.]/g, '' );
        if (element.checked)
            sum += Number(number);
        else
            sum -= Number(number);
        document.getElementById("test").innerHTML = sum;
} 

Demo fiddle : http://jsfiddle.net/lparcerisa/08hLc37a/

With jQuery, it could be done this way:

$("input[type=checkbox]").click(function(){
    var sum=0;
    $("input[type=checkbox]:checked").each(function(index){
        sum += Number($(this).val().replace( /[^\d.]/g,''));
    });
    $("#test").html(sum);
} );

Demo fiddle (jquery) : http://jsfiddle.net/lparcerisa/res4k96j/2/

Sign up to request clarification or add additional context in comments.

Comments

0

One approach (given the revised HTML, below the jQuery) is:

function toggleCheckbox(element) {
    if (element.checked) {
        var number = element.value.replace(/[^\d.]/g, '');
        document.getElementById("test").innerHTML += " " + number;
    }
}

// binding the change-event handler using jQuery, outside of the HTML:    
$('input[type="checkbox"]').on('change', function () {
    toggleCheckbox(this);
});

// binding the click-event handler:
$('#total').on('click', function(){
    // using split() to get an array of the numbers:
    var numbers = $('#test').text().split(' '),
    // using Array.reduce() to iterate over the elements of the array:
        total = numbers.reduce(function(a,b) {
            // using '(+a) + (+b)' to coerce the array elements to numbers
            // (from strings) and then summing them together:
            return (+a) + (+b);
        });
    // setting the text of the '#result' element:
    $('#result').text('(' + total + ')');
});

JS Fiddle demo.

Revised HTML:

<input type="checkbox" value="abc 1 def" name="1" />
<input type="checkbox" value="abc 2 def" name="2" />
<input type="checkbox" value="abc 3 def" name="3" />
<button id="total">Find the total</button>
<span id="test"></span><span id="result"></span>

References:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.