I use the fantastic iCheck plugin to style my checkboxes in my form.
With the plugin, I am able to just call $('input').iCheck()
to apply the desired look and functionality.
However, I am stuck at calling the .iCheck()
function on dynamically created checkboxes.
In an ajax call, I build my checkboxes as follows in the success function; This is in an $.each
block but for simplicity purposes, I've only included code within the statement.
var chk = $('<div><input id="' + n.ID + '" type="checkbox" name="lblChk"><label for="' + n.ID + '">' + n.Title + '</label></div>');
el.append(chk);
Where el
is a div with the id of container
that already exists in the DOM tree and n
is my object returned as JSON
After building the checkboxes and I call $('#container input').iCheck();
obviously I get nothing special but standard checkboxes. I presume it is because the checkboxes are created dynamically and after the .iCheck()
is called. But even after I create checkboxes and call .iCheck()
the result is the same.
Can anyone guide me on this?
Try this
$('#container').iCheck({checkboxClass: 'icheckbox_flat-green',radioClass: 'iradio_flat-green'});
Also there is another situation ... when iCheck has Callbacks
This code won't work for the ajax-loaded inputs, since it's a replacement of bind():
$('#mycheckbox').on('ifChecked', function(event) {
alert();
});
Delegated events should be used instead:
$(document).on('ifChecked', '#mycheckbox', function(event) {
alert('done');
});
Try this...
$('#container').find('input').iCheck();
have you tried checking length of $('#container input')
? I am not sure but input is not the direct child of container
so might not be found with selector $('#container input')
.
Well, I had a similar problem sometime ago and solved it like this:
Assuming that the el
variable is a jQuery element I'll bind the plugin iCheck's initialization to the el
's fully load, so:
This code should be placed after AJAX appends data
el.ready(function() {
$('#container input').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass: 'iradio_flat-green' // If you are not using radio don't need this one.
});
});
Remember to adapt the code to the particularities of your HTML structure. Running the above code just after the elements are appended to the page you are initializing the iCheck of these newly added elements, however if you are using the iCheck callbacks, the plugin will only work if you declare these callbacks correctly, delegating the events to the appropriate tags just as Florin warned.
This code should be placed on the iCheck first initialization
$(document).on('ifChecked', '#mycheckbox', function() {
$(this).addClass('selected');
});
$(document).on('ifUnchecked', '#mycheckbox', function() {
$(this).removeClass('selected');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With