Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .change not updating field

I have a form with 16 checkboxes. I'm trying to track the quantity of boxes checked and provide immediate feedback below the form, but I can't get the numSelected variable to update on change.

Here is my script:

$(document).ready(function () {
// the jQuery.iCheck library wraps the input in a div for styling   
$('input').iCheck({
    checkboxClass: 'icheckbox_square-red'
});

// count the checkboxes
var cb = $(":checkbox"),
    numSelected = 0,
    numLeft = 2 - parseInt(numSelected, 10);
$(cb).change(function () {
    //alert("a checkbox was checked!");
    var $this = $(this);         
    var numSelected = $this(':checked').length;
    $('#status-box').html("Out of "+$this.length+" images you have selected "+numSelected+" for processing, you have "+numLeft+" remaining");
});
});

Here is a jsfiddle I put together, any help is appreciated!

like image 965
Gary D Avatar asked Dec 04 '25 05:12

Gary D


1 Answers

Check the plugin's provided callbacks API. So basically using the ifToggled callback:

var $cb = $('input:checkbox');
$cb.iCheck({
    checkboxClass: 'icheckbox_square-red'
}).on('ifToggled', function() {
    var numSelected = $cb.filter(':checked').length,
        numLeft = 2 - numSelected;
    $('#status-box').html("Out of "+$cb.length+" images you have selected "+numSelected+" for processing, you have "+numLeft+" remaining");
});

Fiddle

Not sure whether the negative remaining number was intended, but as that seems off-topic I'll leave the business logic bit up to you. =]

like image 77
Fabrício Matté Avatar answered Dec 05 '25 19:12

Fabrício Matté