How to check if a checkbox is checked using icheck library
In this tutorial I will show you the easiest way to check if a checkbox is checked using icheck library. As you will see in the following there is no difference on how you check on a normal checkbox and icheck. The single difference is that you need to change few lines of code and update them according to icheck rules. So, to make our example more interesting we will use multiple checkboxes and we will check for each one. So our html will look like the following:
<div class="item"> <label><input type="checkbox" name="test">Checkbox 1</label> </div> <div class="item"> <label><input type="checkbox" name="test1">Checkbox 2</label> </div> <div class="item"> <label><input type="checkbox" name="test2">Checkbox 3</label> </div>
Now, first we will init the icheck on the above html using the following lines of javascript. This example assumes that you already added icheck scripts in your page, if not, go on google and search for icheck and download scripts from their git and load them on your page.
To initialize the icheck use the following js:
if(jQuery('.item').length){ jQuery('.item input').each(function(){ jQuery(this).iCheck({ labelHover: false, cursor: true, handle: 'checkbox' }); }); }
You will have to change the classes, because .item class is quite common so I am sure many of you will use this class to more than chechbox elements.
Now, once we have the html for our checkbox and we have inited them, the only thing we need to do is to check when a checkbox is checked and then you can do everything you need with your code. Using the following code you will be able to check when a checkbox is checked:
jQuery('.item input').each(function(){ jQuery(this).on('ifChanged', function(){ var _this = jQuery(this); if(_this.is(':checked')){ console.log('checked'); }else{ console.log('not checked'); } }); });
This is how you can check when a checkbox is checked using icheck. As you can see we used only a function from icheck library "ifChanged" which fire when a checkbox's state is changed, then we check the checkbox using jquery. Let me know if you encounter any problems in the comments section and I will try to help you.