How to check specific number of checbox and disable remaining using jquery? - javascript

In a specific DIV having .vipGuests that have multiple checkboxes (More than 12), I want to select maximum 12 checkboxes.
As soon as user select 12th checbox then remaining checkbox will get disabled.
My below mentioned code is only counting number of checkbox that are checked. How I can implement the functionality so that user can check maximum 12 checkbox and remaining will get disabled.
$('.vipGuests input[type=checkbox]').on('change', function () {
var totalGuest = 0;
$('.vipGuests input[type=checkbox]:checked').each(function () {
totalGuest++;
});
});
Note: The main thing is that each time during check/uncheck when counter of Checkboxes that are checked is 11 then all checkbox will be active. Only when counter is equals to 12 then the only unchecked checboxes will get disabled.

You can use :not() selector and select un-checked checkbox and disable them. Also you don't need to use .each() to get count of checkbox. Use length property instead.
$(".vipGuests :checkbox").on("change", function(){
if ($(".vipGuests :checkbox:checked").length >= 3)
$(".vipGuests :checkbox:not(:checked)").prop("disabled", true);
else
$(".vipGuests :checkbox:not(:checked)").prop("disabled", false);
});
$(".vipGuests :checkbox").on("change", function(){
$(".vipGuests :checkbox:not(:checked)").prop("disabled", $(".vipGuests :checkbox:checked").length >= 3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vipGuests">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>

You can simply rely on length of jQuery object to check if 12 items are selected.
Use :not(:checked) selector for disabling non-checked inputs.
var $checkboxes = $('.vipGuests input[type=checkbox]');
$checkboxes.on('change', function() {
if ($checkboxes.filter(":checked").length >= 12) {
$checkboxes.filter(":not(:checked)").prop("disabled", true);
} else {
$checkboxes.prop("disabled", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vipGuests">
<input type="checkbox" checked/>1
<input type="checkbox" checked/>2
<input type="checkbox" checked/>3<br/>
<input type="checkbox" checked/>4
<input type="checkbox" checked/>5
<input type="checkbox" checked/>6<br/>
<input type="checkbox" checked/>7
<input type="checkbox" checked/>8
<input type="checkbox" checked/>9<br/>
<input type="checkbox" checked/>10
<input type="checkbox" checked/>11
<input type="checkbox" />12<br/>
<input type="checkbox" />13
<input type="checkbox" />14
<input type="checkbox" />15
</div>

You can use a global variable as below:
var totalGuest = 0;
$(".vipGuests :checkbox").on("change", function(){
this.checked?totalGuest++:totalGuest--;
$checkboxes.filter(":not(:checked)").prop("disabled", (totalGuest>=12)?true:false);
});

Hope this will help you.
JSFiddle Link
Code:
var totalGuest = 0;
$('div input[type=checkbox]').not(":radio,:submit").on('change', function () {
$(this).toggleClass("active");
if($(this).hasClass("active")) {
totalGuest ++;
}
else {
totalGuest --;
}
if(totalGuest >= 12) {
$('input[type=checkbox]').not(".active").attr("disabled","disabled");
}
else {
$('input[type=checkbox]').not(".active").removeAttr("disabled");
}
});

Related

Is there way to click multiple checkboxes when a option(check box) is on and when it is off you can only select one at a time?

I want to be able to perform the functionality in the picture above. It wont work however.
$("#customSwitches").click(function() {
var $this = $(this);
if ($this.data('clicked')) {
alert("not element clicked");
$this.data('clicked', false);
$(document).on('click', "#radio1, #radio2, #radio3, #radio4").not(this).prop('checked', false);
});
} else {
alert("element clicked");
$this.data('clicked', true);
}
});
In each click of the check box from the groups, you can checked the checked property of #customSwitches. If it is not checked then you can count the length of checked check boxes from the group, if it is more than 1 then you can prevent the default event.
When clicking #customSwitches you can reset all the check boxes from the group.
You can try the following way:
$(".vehicle").click(function(e){
if($('#customSwitches').is(':not(:checked)')){
if($('.vehicle:checked').length > 1){
alert('You can not check multiple');
e.preventDefault();
}
}
});
$("#customSwitches").click(function(e){
$(".vehicle").prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="customSwitches"> Select Multiple</label><input type="checkbox" id="customSwitches">
<hr/>
<input class="vehicle" type="checkbox" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label>
<input class="vehicle" type="checkbox" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label>
<input class="vehicle" type="checkbox" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
Your current code has some syntax issues and uses nested event handlers, which is not a good design pattern.
In basic terms you are trying to build a dynamic checkbox limiter based on the first checkbox state. To do that simply determine if the first box is checked, and then count the number of checked regions to see if it exceeds the limit. If so, disallow the current box to be checked. Try this:
let $allowMulti = $('#allow_multi').on('change', function() {
if (!this.checked)
$('.region').prop('checked', false); // remove all checks if no multi allowed
});
$('.region').on('change', function() {
let selectedCount = $('.region:checked').length;
if (!$allowMulti.prop('checked') && selectedCount > 1)
$(this).prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<label>
<input type="checkbox" id="allow_multi">
Select multiple regions
</label>
</p>
<label>
<input type="checkbox" class="region" value="1"> 1
</label>
<label>
<input type="checkbox" class="region" value="2"> 2
</label>
<label>
<input type="checkbox" class="region" value="3"> 3
</label>
<label>
<input type="checkbox" class="region" value="4"> 4
</label>

Adding and removing from count when checkbox is checked/unchecked with javascript/jquery?

I'm relatively new to JS, so I'm getting a little stuck with this:
Let's say I have 40 checkboxes, but a user can select no more than 10.
I have the checkboxes set out, labelled checkbox1, checkbox2 etc right up to 40. The user cannot select more than 10. How would I go about doing this?
The way I thought of doing it would be like this, but I'm unsure whether or not this would work, due to obviously having 40 fields and then what if they uncheck one?
function checkValidation() {
if (document.getElementById('checkbox1').isChecked()) {
document.getElementById('validation').value() + 1;
}
}
So every time it's checked, it would add 1 to the textbox validation and then I could do an if statement to say if validation.value() > 8 then alert out to say they can't check anymore.
I think that's not the best way, as if they uncheck the box, my function won't take this in consideration?
Hopefully this makes sense, if anything needs clarification please let me know and I can explain further.
Try the following way:
$('#myBtn').click(function(){
var countCheckd = $('input[type=checkbox]:checked').length;
if(countCheckd >= 3){
console.log('You have 3 or more checked: ' +countCheckd);
}
else{
console.log('You have less than 3 checked: ' +countCheckd);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />1
<input type="checkbox" />2
<input type="checkbox" />3
<input type="checkbox" />4
<input type="checkbox" />5
<br><br>
<input type="button" id="myBtn" value="Check"/>
You can add a class on all your considered checkboxe, called for example chk.
Then you declare your count function :
function countCheck(){
return $(".chk:checked").length;
}
Finally you add an event on your checkboxes click :
$(document).on("click",".chk",function(){
var numberChecked = countCheck();
//update your input
$("#validation").val(numberChecked );
});
Just make an event of checkbox click and check for the count of each click, in below example if the click is exceeded then 5 it gives an alert message and won't be allowed to click more checkboxes.
$(function(){
for(var i=0;i<=30;i++){
$(".test").append("checkbox "+i+"<input type='checkbox' name='chk[]' class='check' id='check_"+i+"'><br />");
}
})
$(document).on("click",".check",function(){
var checked = $(".check:checked").length
if(checked > 5){
alert("Maximum 5");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='test'>
</div>
You can try something like this:
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 10) {
$(this).prop('checked', false);
alert("Only 10 selection is allowed");
}
});
This code is unchecking previous checkbox if checked input's length more than 10:
$('input[type="checkbox"]').on('click', function(){
var max=0;
var t=$(this);
$('input[type="checkbox"]:checked').each(function(){
if($(this).data('oops')>max){
max=$(this).data('oops');
}
});
t.data('oops', (max+1));
if($('input[type="checkbox"]:checked').length>10){
$('input[type="checkbox"]:checked').each(function(){
if($(this).data('oops')==max){
$(this).prop('checked', false);
}
});
}
});
Without adding global variable.
See
This works:
// these are global variables
var checkBoxChecks = 0;
var maxChecks = 10;
$('input[type="checkbox"]').on('click', function()
{
// if the currently clicked checkbox is now checked
if(this.checked)
{
if(checkBoxChecks < maxChecks) checkBoxChecks++;
else
{
this.checked = false;
alert("You have reached the maximum amount of " + maxChecks + " checks.");
}
}
else checkBoxChecks--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />

Setting checkboxes using Jquery

I have a dynamic form that has a number of checkboxes in it. I want to create a "select all" method that when clicked automatically checks all the boxes in the form.
[x] select all //<input type="checkbox" id="select-all"> Select all
[] item 1 //<input type="checkbox" id="1" class="checkbox1" value="1">
[] item 2 //<input type="checkbox" id="2" class="checkbox1" value="2">
[submit]
My jQuery is as follows:
$(document).ready(function(){
$('#select-all').click(function() {
if (this.checked)
{
console.log("Check detected");
$('.checkbox1').each(function() {
console.log('Checking the item with value:' + this.value );
$(this).prop('checked', true);
console.log(this);
});
} else {
console.log("not checked");
}
});
});
My console output:
> Check detected
> Checking the item with value:1
> <input type=​"checkbox" id=​"1" class=​"checkbox1" value=​"1">​
> Checking the item with value:2
> <input type=​"checkbox" id=​"2" class=​"checkbox1" value=​"2">​
I am able to loop through each item however, I am not sure how to actually set the checkbox to checked.
The part I am struggling with is the actual setting of the checked state, I know I need to use: .prop('checked',true) however, what do I use for the actual element? $(this) obviously does not work...
$(this).prop('checked', true);
Use this simple code
$(".checkAll").change(function(){
$('.checkbox1').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Check all</label>
<input type="checkbox" class="checkAll" />
<br/><br/>
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />
You are referring #select-all as (this.checked) ,You need to refer as $(this).
Secondly you can use :checked to find out if it is checked or not.
Thirdly you dont need to loop over $('.checkbox1'). jquery will match all elements and will update the attribute.
Below is the snippet which may be helpful
$(document).ready(function() {
$('#select-all').click(function() {
if ($(this).is(":checked")) {
console.log("Check detected");
$('.checkbox1').prop('checked', true)
} else {
$('.checkbox1').prop('checked', false)
}
});
// If select-all is selected and if one check box is unchecked ,
//then select-all will be unchecked
$('.checkbox1').click(function(event) {
if ($(this).is(':checked')) {
// #select-all must be checked when all checkbox are checked
} else {
if ($('#select-all').is(':checked')) {
$('#select-all').prop('checked', false)
}
}
})
});
JSFIDDLE
demo link
js code
$('.checkbox1').click(function(event) {
var _this = $(this);
if (!_this.prop('checked')) {
$('#select-all').prop('checked', false)
}
})
$('#select-all').click(function() {
var _this = $(this);
var _value = _this.prop('checked');
console.log("Check detected");
$('.checkbox1').each(function() {
console.log('Checking the item with value:' + this.value);
$(this).prop('checked', _value);
console.log(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="select-all"> Select all
<input type="checkbox" id="1" class="checkbox1" value="1">
<input type="checkbox" id="2" class="checkbox1" value="2">
Just to answer this question. I tried the various solutions offered and they appeared not to work. However I then realised that due to using Jquery Uniform I needed to add an additional bit of code to get the display to work correctly:
This post was helpful.
Thank you to all who have taken the time to answer.
My final code:
$(document).ready(function(){
$('#select-all').click(function() {
if (this.checked)
{
$('.checkbox1').prop('checked', true);
} else {
$('.checkbox1').prop('checked', false);
}
$.uniform.update('.checkbox1');
});
});

How to select all checkbox using jquery or javascript? [duplicate]

This question already has answers here:
How to select all checkboxes with jQuery?
(15 answers)
Closed 8 years ago.
I have multiple checkboxes , there is a checkbox with select all name, now i want that when some tick
the select all checkbox, then all the checkbox must be selected. I think this will be in jquery.
any tutorial link or codes with hints would be appreciated.the code snip is under...
<input type="checkbox" value="">Select All<br/>
<input type="checkbox" value="">A<br/>
<input type="checkbox" value="">B<br/>
<input type="checkbox" value="">C<br/>
<input type="checkbox" value="">D<br/>
<input type="checkbox" value="">E<br/>
<input type="checkbox" value="">F<br/>
<input type="checkbox" value="">G<br/>
<input type="checkbox" value="">H<br/>
This should check all checkboxes when you check the "Select All" one, and also uncheck all checkboxes when you uncheck it.
$("#selectAll").click(function () {
$(":checkbox").not(this).prop("checked", $(this).is(":checked"));
});
If you don't want the uncheck behavior:
$("#selectAll").click(function () {
if ($(this).is(":checked")) {
$(":checkbox").not(this).prop("checked", true);
}
});
But of course, you must identify it. Do it by adding the id="selectAll" attribute (or any other id you wish, just make sure you change the JavaScript code as well):
<input type="checkbox" value="" id="selectAll">Select All<br/>
<input type="checkbox" value="">A<br/>
<input type="checkbox" value="">B<br/>
<input type="checkbox" value="">C<br/>
<input type="checkbox" value="">D<br/>
<input type="checkbox" value="">E<br/>
<input type="checkbox" value="">F<br/>
<input type="checkbox" value="">G<br/>
<input type="checkbox" value="">H<br/>
<input type="checkbox" id="exp" />Tick All Checkbox<br/>
<input type="checkbox" value="demo1" class="subchkbox"/>No 1<br/>
<input type="checkbox" value="demo2" class="subchkbox"/>No 2<br/>
<input type="checkbox" value="demo3" class="subchkbox"/>No 3<br/>
<input type="checkbox" value="demo4" class="subchkbox"/>No 4<br/>
<input type="checkbox" value="demo5" class="subchkbox"/>No 5<br/>
<sctipt type="text/javascript">
/*Include the jquery library 1.9.1*/
$(document).ready(function() {
$('#exp').click(function(event) {
if(this.checked) {
$('.subchkbox').each(function() {
this.checked = true;
});
}else{
$('.subchkbox').each(function() {
this.checked = false;
});
}
});
});
[the fiddle is here][1]
Using jQuery :
$("input[type=checkbox]").prop({ checked : true })
JSFiddle
Using pure JavaScript :
var inputs = document.querySelectorAll('input[type=checkbox]')
Object.keys(inputs).forEach(function(i){
inputs[i].checked = true
})
JSFiddle
$("checkboxContainer").find("input[type='checkbox']").each(function() {
$(this).prop("checked", true);
});
I think using .find() is faster when selecting multiple elements.
If you want to do this in plain JS, it's also pretty simple.
You just have to loop through all of the inputs and set checked to true (or false), which isn't very efficient.
document.getElementById("all").addEventListener("change", function() {
if (this.checked) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].type === "checkbox") {
boxes[i].checked = true;
}
}
} else {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].type === "checkbox") {
boxes[i].checked = false;
}
}
}
});
<input type="checkbox" value="" id="all">Select All
<br/>
<input type="checkbox" value="">A
<br/>
<input type="checkbox" value="">B
<br/>
<input type="checkbox" value="">C
<br/>
<input type="checkbox" value="">D
<br/>
<input type="checkbox" value="">E
<br/>
<input type="checkbox" value="">F
<br/>
<input type="checkbox" value="">G
<br/>
<input type="checkbox" value="">H
<br/>
Derived from the current answer marked as correct, it can all be much simpler:
$(document).ready(function()
{
$('#exp').click(function(event)
{
$('.subchkbox').prop({
checked: $(this).prop('checked')
});
});
});

Check all other checkboxes when one is checked

I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):
<div id="ScrollCB">
<input type="checkbox" name="ALL" value="checked" checked="checked">
All (if nothing selected, this is default) <br>
<c:forEach items="${serviceList}" var="service">
<input type="checkbox" name="${service}" value="checked"> ${service} <br>
</c:forEach>
</div>
What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).
I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):
<script type="text/javascript">
$ui.find('#ScrollCB').find('label[for="ALL"]').prev().bind('click',function(){
$(this).parent().siblings().find(':checkbox').attr('checked',this.checked).attr('disabled',this.checked);
}); });
</script>
Could you tell me some simple approach how to get it work? Thanks a lot!
demo
updated_demo
HTML:
<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
JS:
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('div input').attr('checked', true);
} else {
$('div input').attr('checked', false);
}
});
HTML:
<form>
<label>
<input type="checkbox" id="selectall"/> Select all
</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
</form>
JS:
$('#selectall').click(function() {
$(this.form.elements).filter(':checkbox').prop('checked', this.checked);
});
http://jsfiddle.net/wDnAd/1/
Thanks to #Ashish, I have expanded it slightly to allow the "master" checkbox to be automatically checked or unchecked, if you manually tick all the sub checkboxes.
FIDDLE
HTML
<label><input type="checkbox" name="sample" class="selectall"/>Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox1</label><br/>
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox4</label><br />
</div>
SCRIPT
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('input:checkbox').prop('checked', true);
} else {
$('input:checkbox').prop('checked', false);
}
});
And now add this to manage the master checkbox as well...
$("input[type='checkbox'].justone").change(function(){
var a = $("input[type='checkbox'].justone");
if(a.length == a.filter(":checked").length){
$('.selectall').prop('checked', true);
}
else {
$('.selectall').prop('checked', false);
}
});
Add extra script according to your checkbox group:
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('colors[]');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
HTML Code:
<input type="checkbox" id="selectall" onClick="selectAll(this,'color')" />Select All
<ul>
<li><input type="checkbox" name="colors[]" value="red" />Red</li>
<li><input type="checkbox" name="colors[]" value="blue" />Blue</li>
<li><input type="checkbox" name="colors[]" value="green" />Green</li>
<li><input type="checkbox" name="colors[]" value="black" />Black</li>
</ul>
use this i hope to help you i know that this is a late answer but if any one come here again
$("#all").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Only in JavaScript with auto check/uncheck functionality of master when any child is checked/unchecked.
function FnCheckAll()
{
var ChildChkBoxes = document.getElementsByName("ChildCheckBox");
for (i = 0; i < ChildChkBoxes.length; i++)
{
ChildChkBoxes[i].checked = document.forms[0].CheckAll.checked;
}
}
function FnCheckChild()
{
if (document.forms[0].ChildCheckBox.length > document.querySelectorAll('input[name="ChildCheckBox"]:checked').length)
document.forms[0].CheckAll.checked = false;
else
document.forms[0].CheckAll.checked = true;
}
Master CheckBox:
<input type="checkbox" name="CheckAll" id="CheckAll" onchange="FnCheckAll()" />
Child CheckBox:
<input type="checkbox" name="ChildCheckBox" id="ChildCheckBox" onchange="FnCheckChild()" value="#employee.Id" />```
You can use jQuery like so:
jQuery
$('[name="ALL"]:checkbox').change(function () {
if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
else $('input:checkbox').removeAttr('checked');
});
A fiddle.
var selectedIds = [];
function toggle(source) {
checkboxes = document.getElementsByName('ALL');
for ( var i in checkboxes)
checkboxes[i].checked = source.checked;
}
function addSelects() {
var ids = document.getElementsByName('ALL');
for ( var i = 0; i < ids.length; i++) {
if (ids[i].checked == true) {
selectedIds.push(ids[i].value);
}
}
}
In HTML:
Master Check box <input type="checkbox" onClick="toggle(this);">
Other Check boxes <input type="checkbox" name="ALL">
You can use the :first selector to find the first input and bind the change event to it. In my example below I use the :checked state of the first input to define the state of it's siblings. I would also suggest to put the code in the JQuery ready event.
$('document').ready(function(){
$('#ScrollCB input:first').bind('change', function() {
var first = $(this);
first.siblings().attr('checked', first.is(':checked'));
});
});
I am not sure why you would use a label when you have a name on the checkbox. Use that as the selector. Plus your code has no labels in the HTML markup so it will not find anything.
Here is the basic idea
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings().prop("checked",this.checked);
});
if there are other elements that are siblings, than you would beed to filter the siblings
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings(":checkbox").prop("checked",this.checked);
});
jsFiddle

Categories

Resources