I'm working with iCheck and I'd like to modify the element skin whenever its state changes (e.g. grey for unchecked and green for checked). Here's what I've tried so far:
<!-- the html element I'm trying to change -->
<input type="checkbox" name="status" id="status" class="icheck">
<label for="status">Active</label>
//initializing fields
$('.icheck').each(function() {
var self = $(this),
label = self.next(),
label_text = label.text();
label.remove();
self.iCheck({
checkboxClass: 'icheckbox_line-grey',
radioClass: 'iradio_line-grey',
insert: '<div class="icheck_line-icon"></div>' + label_text
});
});
//how I'm trying to make it work
$('.icheck').on('ifChanged', function() {
var self = $(this);
var label = self.parent();
var label_text = label.text();
var checkboxClass;
var radioClass;
if (label_text == 'Ativado') {
checkboxClass = 'icheckbox_line-grey';
radioClass = 'iradio_line-grey';
label_text = 'Desativado'
} else if (label_text == 'Desativado') {
checkboxClass = 'icheckbox_line-green';
radioClass = 'iradio_line-green';
label_text = 'Ativado'
}
self.iCheck({
checkboxClass: checkboxClass,
radioClass: radioClass,
insert: '<div class="icheck_line-icon"></div>' + label_text
});
});
However, the code above manages to change the element skin only once.
What am I missing here in order to make it work?
Within the ifChanged event you update the iCheck.
Refer to:
Now, your ifChanged event does not work anymore because a new element (iCheck) is created on the fly to replace the old one. Hence you need a different event binding: delegation:
Moreover, because you start with an inactive state you need to change this line:
to: