how to limit the checkbox checked using icheck jquery plugin? - javascript

How to limit the checkbox checked using iCheck jquery plugin. Please check wiht jsfiddle
$('input').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass: 'iradio_flat-green',
labelHover: true,
});
});
https://jsfiddle.net/s9916jpy/2/

DEMO
Add an ifChecked event to all the checkbox with its common class i.e. .men_checkbox and check whether checked checkbox length is greater than or equal to limit which is a global variable as below:
var limit=4; //change according to your need
$(".men_checkbox").on("ifChecked",function(){
var checkboxes = $("input:checkbox");//get all the checkbox
if (checkboxes.filter(":checked").length >= limit) {
//if limit is reached disbaled all except checked and #man7
//else put an alert here instead of below lines.
checkboxes.not(":checked,#man7").iCheck('disable');
} else {
//else enable it all
checkboxes.not(":checked").iCheck('enable');
}
});
UPDATE
To display an alert you just need to prevent its default action using e.preventDefault() and display the alert. Check below code and this DEMO
$(".men_checkbox").on("ifChecked",function(e){
var checkboxes = $("input:checkbox");
var $this=$(this);
if (checkboxes.filter(":checked").length > limit) {
alert('Max limit reached');
setTimeout(function(){
$this.iCheck('uncheck');
},1);
}
});

Related

Check whether the selected row has a checked check box

How can I check if the selected row has a column check box checked?
I can get the column innerHTML which says <input type="checkbox"> but how to check if its checked or not.
I want to see if the CB is checked?
var l_iNoOfRows=$("#imageResultsList tr").length;
for(var i=1;i<=l_iNoOfRows;i++){
var l_oSelectedRow =$("#imageResultsList tr")[i]
var l_sCbColumn =l_oSelectedRow.cells[l_iCB].innerHTML;
}
If you can get the checkbox and create a jQuery object out of it, you can use the prop method to find the value of its 'checked' property.
$yourCheckboxElement.prop('checked') will return a boolean, true if it is checked and false if it is not.
You can count checked check boxes with below codes.
var c = $(l_oSelectedRow.cells[l_iCB]).find("input[type='checkbox']:checked").length;
and detect rows had checked check box.
if (c > 0) {
// checked check box is existed.
} else {
// checked check box is now existed.
}
FIDDLE
$('.btn').click(function () {
$('#table').find("input:checkbox:checked").each(function () {
var check = $(this).closest('tr').index();
alert(check);
});
});
Iterate through all the checked checkbox and get the index of the closest tr
FIDDLE
$('.btn').click(function () {
var index =$('.input').val();
var row = $('#table').find('tr:nth-child('+index+')').find('input:checkbox')
if(row.is(':checked')){
alert(index);
}else{
alert('no check box check');
}
});
IF you want to check the row if there is a checked check get the row number use it as selector then check that row if there is a checked checkbox
A better (and easier) way to do this is like this
$("#imageResultsList tr").each(function(){
var cb = $(this).find('input [type="checkbox"]');
if(cb.prop('checked')){
alert('Checked');
} else {
alert('Not Checked');
}
});
Use jQuerys .prop function
See documentation: http://api.jquery.com/prop/
<label for="checkbox">Checkbox</label>
<input id="checkbox" type="checkbox" />
$('input[type="checkbox"]').on('click', function() {
alert($(this).prop('checked'));
});
Example:
https://jsfiddle.net/a26sw7ba/2/
In your case you could do the following with jQuery:
var l_iNoOfRows=$("#imageResultsList tr").length;
for(var i=1;i<=l_iNoOfRows;i++){
var l_oSelectedRow =$("#imageResultsList tr")[i]
var l_sCbColumn =l_oSelectedRow.cells[l_iCB].innerHTML;
alert($(l_sCbColum).prop('checked'));
}
Obviously replacing the alert with what ever statement needed to accomplish your goals.

Uncheck a Checkbox using Jquery

I have a page with a list of check boxes, when a check box is checked I am updating the number of check boxes selected in side a p tag. This is all working.
The problem I have is when the user selects more than 5 checkboxes I want to use Jquery to unselect it.
This is what I have so far, the first if else works but the first part of the if doe
$("input").click(function () {
if ($("input:checked").size() > 5) {
this.attr('checked', false) // Unchecks it
}
else {
$("#numberOfSelectedOptions").html("Selected: " + $("input:checked").size());
}
});
Any ideas?
Firstly you should use the change event when dealing with checkboxes so that it caters for users who navigate via the keyboard only. Secondly, if the number of selected checkboxes is already 5 or greater you can stop the selection of the current checkbox by using preventDefault(). Try this:
$("input").change(function (e) {
var $inputs = $('input:checked');
if ($inputs.length > 5 && this.checked) {
this.checked = false;
e.preventDefault();
} else {
$("#numberOfSelectedOptions").html("Selected: " + $inputs.length);
}
});
Example fiddle
Note I restricted the fiddle to 2 selections so that it's easier to test.
You need this $(this).prop('checked', false);
You should be saying
$(this).attr('checked', false)
instead of
this.attr('checked', false)
You need this $(this).prop('checked', false);
Also this is a javascript object, if you want to use jquery you should prefer $(this).

Multiple checkboxes jquery manual clicked checkbox fires, but 'code clicked' one doesn't

I have multiple checkboxes that when all are checked - they check a parent checkbox. When that parent checkbox is checked an alert is fired and an image is faded in...
The problem is that when the parent checkboxes are checked using jquery they do not show the alert or swap the image, it only works when the checkbox is checked manually.
Here is my code:
// Parent Checkboxes -multiple checkboxes
$("input[type='checkbox'].PARENT-CHECKBOXES").change(function(){
var a = $("input[type='checkbox'].PARENT-CHECKBOXES");
if(a.length == a.filter(":checked").length){
alert('ACTION COMPLETED');
TweenMax.to("#fade-in-image", 0.1, {autoAlpha: 1});
}
});
// Child Checkboxes -multiple checkboxes
$("input[type='checkbox'].CHILD-CHECKBOX").change(function(){
var step1 = $("input[type='checkbox'].CHILD-CHECKBOX");
if(step1.length == step1.filter(":checked").length){
alert('SKU OPERATION COMPLETE');
$("#PARENT-CHECKBOX1").prop("checked", true);
}
});
EDIT: So I edited my code and this is the working result.
var a = $("input[type='checkbox'].PARENT-CHECKBOXES");
$("input[type='checkbox'].CHILD-CHECKBOX").change(function(){
var step2 = $("input[type='checkbox'].CHILD-CHECKBOX");
if(step2.length == step2.filter(":checked").length){
alert('Operation Complete');
$("#PARENT-CHECKBOX1").prop("checked", true).change();
}
if(a.length == a.filter(":checked").length){
alert('ACTION COMPLETED');
TweenMax.to("#fade-in-image", 0.1, {autoAlpha: 1});
}
});
When you check/uncheck checkbox programmatically, it doesn't trigger automatically (as you already experienced). You need to use .trigger() to trigger the change event.
code
$("#PARENT-CHECKBOX1").trigger("change");
or
$("#PARENT-CHECKBOX1").change();
You need to trigger change event after checking - it doesn't trigger automatically - like this:
$("#PARENT-CHECKBOX1").prop("checked", true).trigger("change");

Set of actions before enabling submit button

I want my form to meet a set of criterias before the submit button gets enabled, my form is in this order:
Text field, value has to be over 150
Set of radio selects, 1 has to be selected
TOS box, has to be checked
So far I have this:
if ((parseInt($('#amount').val(), 10) > 149) && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
{
// Enable Button here
}
Do I have to add this to everything I'm checking, for example keyup on the textfield, change on the select and checkbox and set true in variables that those fields are "OK" or how do I do it ?
You need to create a custom validate function, which you have to run onchange of your text field, and on click of your radio and checkbox click event.
Following psudo code might help you.
var textFieldValidationPassed = false;
function validateFormFields() {
//First checks if text field length is not less then 150.
// then check if one of the radio button is selected.
// then check for TOS box checked state;
if (textFieldValidationPassed && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
// enable submit button;
}
}
$('input:radio[name="radioset1"]', 'input.checkbox_check').click(function() {
validateFormFields();
})
$('#amount').keyup(function(){
if($(this).val().length > 149) {
textFieldValidationPassed =true;
validateFormFields();
}
})
it is a workaround but will work, make submit button initially...
$(":submit").on('focus',Validate);
function Validate(){
if ((parseInt($('#amount').val(), 10) > 149) && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
{
// Enable Button here
}
else
{
//Disable button
}
}
You can just add click, change events at once like this
$("input").on("change, click", function(){
});
Write your logic within this.
Also you've checkbox validation wrong. Check box will be clicked.
$('input.checkbox_check').prop('checked')
Here is the complete code
$(function(){
$("input").on("change, click", function(){
if ((parseInt($('#UserName').val(), 10) > 149) && $('input:radio[name="gender"]').is(':checked') && $("#remember").prop('checked'))
{
$("#submit").removeAttr("disabled");
}
else{
$("#submit").attr("disabled", "disabled");
}
});
});
WORKING FIDDLE
You can use jQuery.validate. You can define custom validation methods too.
http://jqueryvalidation.org
You can use HTML5 validation. For example:
<input type="checkbox" required name="checkbox1" />
<input type="text" min="150" name="input1" />
You can see another example here http://www.w3schools.com/html/html5_form_attributes.asp
You can call it at textbox, radiobutton and checkbox onchange events.
EDIT:
$(document).ready(function () {
$("input").change(function () {
//call function.
});
});

How can I check if a checkbox is checked on click?

I need to trigger some code when I click a checkbox based on if a checkbox is checked or not.
But for some reason, .is(':checked') is always triggered.
This is my code.
jQuery('#selectlist input[type=checkbox]').live('click',function(){
var select_id = jQuery(this).attr('id');
if(jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
// Remove some data from variable
} else {
alert('You have checked the checkbox');
//Add data to variable
}
}
UPDATE
I've added an example on JSFiddle: http://jsfiddle.net/HgQUS/
Use change instead of click
$(this).val();
or
$(this).prop('checked'); # on jquery >= 1.6
You will be better at searching over SO:
Get checkbox value in jQuery
How to retrieve checkboxes values in jQuery
Testing if a checkbox is checked with jQuery
this.checked
Should tell you if the checkbox is checked or not although this is just javascript so you won't be able to call it on a 'jquery' element. For example -
<input type="checkbox" id="checky">
$("#checky")[0].checked
If the input has the checked attribute, then it is obviously checked, it is removed if it is not checked.
if ($(this).attr("checked")) {
// return true
}
else {
// return false
}
However, you can adapt the above code to check if the attribute, if it is not removed and instead set to true/false, to the following:
if ($(this).attr("checked") == "true") {
// return true
}
else {
// return false
}
Additionally, I see you use jQuery as an operator for selectors, you can just use the dollar, $, symbol as that is a shortcut.
I flipped-flopped the alerts, and it works for me:
<script type="text/javascript">
jQuery('#selectlist input[type=checkbox]').live('click',function(){
var select_id = jQuery(this).attr('id');
if(jQuery(this).is(':checked')) {
alert('You have checked the checkbox');
// Remove some data from variable
} else {
alert('You have unchecked the checkbox');
//Add data to variable
}
});
</script>
Your "if" syntax is not correct.
jQuery('#selectlist_categories input[type=checkbox]').live('click',function(){
var cat_id = jQuery(this).attr('id');
// if the checkbox is not checked then alert "You have unchecked the checkbox"
if(!jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
} else {
//else alert "You have checked the checkbox"
alert('You have checked the checkbox');
}
});
if you're confused about why it says unchecked when you check it. There is nothing wrong with your code you can just switch the unchecked and checked with each other in the alerts like this:
$('#selectlist_categories input[type=checkbox]').on('change',function(){
var cat_id = $(this).attr('id');
let cat_idText = $("input[type=checkbox]:checked").val();
if(jQuery(this).is(':checked')) {
alert('You have checked the checkbox' + " " + `${cat_idText}`);
} else {
alert('You have unchecked the checkbox');
}
});
PS: I have updated the script to work in jQuery 3.5.1 the original with the live() only works on jQuery 1.7 since it was removed in 1.9 to instead use on() and on jQuery 3.5.1 you can use $ instead of jQuery and the val() function works on all versions because it added in jQuery 1.0
Or in a nice better fashion correct the if statement as RickyCheers said adding the ! before jQuery or $ which then the if statement will turn it into a if jQuery Element is not checked
$('#selectlist_categories input[type=checkbox]').on('click',function(){
var cat_id = $(this).attr('id');
if(!jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
} else {
alert('You have checked the checkbox');
}
});

Categories