我有一个带有16个复选框的表单。我试图跟踪已选中的框的数量,并在表格下方提供即时反馈,但是我无法获取numSelected变量来更新更改。
这是我的脚本:
$(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");
});
});
这是我放在一起的jsfiddle,感谢您的帮助!
最佳答案
检查插件提供的callbacks API。因此,基本上使用ifToggled
回调:
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
不确定是否打算使用负的剩余数字,但是由于这似乎是题外话,我将把业务逻辑留给您。
=]