drunkonmilk drunkonmilk - 4 months ago 10
jQuery Question

Update div with values from checkbox

I want to be able to update a div immediately when I select any checkbox. I am currently able to do so, however, when I check the "select all" checkbox to select all the checkboxes, it doesn't update my div with the information from my checkboxes.

Here's what I have done so far: https://jsfiddle.net/3rxk043v/2/

My HTML:

<div id="item-list"></div>
<p>Total:<span class="total"></span></p>
<label><input type="checkbox" id="selectall" class="c-check">select all</label>
<label><input type="checkbox"class="selectcheckbox selectedtotal" name="items" value="Thomas Hobbes_100" data-amt="100">Thomas</label>
<label><input type="checkbox"class="selectcheckbox selectedtotal" name="items" value="Jerry Xavier_150" data-amt="150">Jerry</label>
<label><input type="checkbox"class="selectcheckbox selectedtotal" name="items" value="Sam Edith_80" data-amt="80">Sam</label>


JQuery:

$('#selectall').change(function() {
$('.selectcheckbox').prop('checked', this.checked);
});

$('input[name="items"]').change(function () {
var inputVal = $(this).val();
var className = inputVal.replace(/ /g, '_');
var inputArr = inputVal.split('_');

if ($(this).prop('checked')) {
$("#item-list").append('<span class="span_' + className + '"><li>'+ inputArr[0] + '<p>$' + inputArr[1] + '</p></li></span>');
} else {
$('.span_'+className).remove();
}
});

var $calculateselected = $('.selectedtotal').change(function () {
var v = 0;
$calculateselected.filter(':checked').each(function () {
v += $(this).data('amt');
})

var left = 2000-v;
$('.total').html(v);
$('.amtleft').html(left);
});
$('.selectedtotal:checked').change();


Is there anything preventing the updating of the div when clicking on the select all? All the checkboxes become checked but nothing is updated in my div.

UPDATE:
If I were to add ".trigger('change');" to my code, when I select one checkbox (E.g. Thomas) first before selecting the "select all" checkbox, Thomas will be printed twice. How do I prevent this from happening?

Answer

Add the following to your code :

.trigger('change');

to be like this

$('#selectall').change(function() {
    $('.selectcheckbox').prop('checked', this.checked).trigger('change');
});

and keep every thing as is .