Checkbox alert, select max 4 items - javascript

I have a form with checkboxes. Max 4 items needs to be selected. If selecting more then an Alert pops up. I have it working when I use the same name="" but that really needs to be different. Anyone knows how to do this?
The script I have: (ckb needs to be ckb1 + ckb2 + ckb3...)
function chkcontrol(j) {
var total=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.form1.ckb[i].checked){
total =total +1;}
if(total > 4){
alert("Selecteer a.u.b. maximaal 4 workshops")
document.form1.ckb[j].checked = false ;
return false;
}
}
}
My form html code:
<form enctype="application/x-www-form-urlencoded" method="post" name="form1">
<span>Workshops selection: (max 4)</span><br><br>
<input type="checkbox" name="ckb1" value="blabla first" onclick='chkcontrol(0)'; /> blabla first<br>
<input type="checkbox" name="ckb2" value="blabla 2" onclick='chkcontrol(1)'; /> blabla 2<br>
<input type="checkbox" name="ckb3" value="blabla 3" onclick='chkcontrol(2)'; /> blabla 3<br>
<input type="checkbox" name="ckb4" value="blabla 4" onclick='chkcontrol(3)'; /> blabla 4<br>
<input type="checkbox" name="ckb5" value="blabla 5" onclick='chkcontrol(4)'; /> blabla 5<br>
<input type="checkbox" name="ckb6" value="blabla 6" onclick='chkcontrol(5)'; /> blabla 6<br>
<input type="checkbox" name="ckb7" value="blabla 7" onclick='chkcontrol(6)'; /> blabla 7<br>
<input class="btn" class="cursor" name="Sent" type="submit" value="Sent" />
</form>
My fiddle: https://jsfiddle.net/usq2aeLL/1/
Working one but needs different name="xxx": https://jsfiddle.net/usq2aeLL/2/

Use a common class to select the elements instead
<input type="checkbox" name="ckb1" class="myBox" value="blabla first" />
and then
function chkcontrol() {
var total = 0;
var elems = document.querySelectorAll('.myBox');
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked) {
total = total + 1;
}
if (total > 4) {
alert("Selecteer a.u.b. maximaal 4 workshops")
elems.checked = false;
return false;
}
}
}
FIDDLE
Preferably you'd swap out the inline event handlers with addEventListener as well.

Related

How can I add up my selection lists, radios, and checkboxes to total?

I need some guidance in how to add my selection list to my total. I am still new to javascript so i did what i could but for some reason, i cannot figure out how to add the selection list to my total. the textboxes with 0.00 are there for me to see if the radios, checkboxes and selection are adding up properly.
``
`
function customerInfo(cName){
var dinerName = document.getElementById(cName).value;
document.getElementById('cust_name').innerHTML = dinerName;
}
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
function getRadioVal(form, name) {
var radios = form.elements[name];
var val;
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked == true ) {
val = radios[i].value;
break;
}
}
return val;
}
function getToppingsTotal(e) {
var form = this.form;
var val = parseFloat( form.elements['tops_tot'].value );
if ( this.checked == true ) {
val += parseFloat(this.value);
} else {
val -= parseFloat(this.value);
}
form.elements['tops_tot'].value = formatDecimal(val);
updatePizzaTotal(form);
}
function getSizePrice(e) {
this.form.elements['sz_tot'].value = parseFloat( this.value );
updatePizzaTotal(this.form);
}
function getDeliveryPrice(e){
selectElement = document.querySelector('#pick_delivery');
output = selectElement.options[selectElement.selectedIndex].value;
console.log(output);
}
function updatePizzaTotal(form) {
var sz_tot = parseFloat( form.elements['sz_tot'].value );
var tops_tot = parseFloat( form.elements['tops_tot'].value );
form.elements['total'].value = formatDecimal( sz_tot + tops_tot );
}
// removes from global namespace
(function() {
var form = document.getElementById('pizzaForm');
var el = document.getElementById('pizza_toppings');
// input in toppings container element
var tops = el.getElementsByTagName('input');
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
tops[i].onclick = getToppingsTotal;
}
}
var sz = form.elements['size'];
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = getSizePrice;
}
// set sz_tot to value of selected
form.elements['sz_tot'].value = formatDecimal( parseFloat( getRadioVal(form, 'size') ) );
updatePizzaTotal(form);
})(); // end remove from global namespace and invoke
<form name="pizzaOrder" method="post" id="pizzaForm" enctype="text/plain">
<fieldset style="width: 60%;">
<legend>Create Your Pizza</legend>
<h3>Customer's Name:</h3>
<p>
<input type="text" name="client_name" id="client_name" value="First and Last Name" size="30" value="" />
<input type="button" onclick="customerInfo('client_name')" value="Enter"></button>
</p>
<h3>Pick Your Size:</h3>
<p>
<label><input type="radio" name="size" value="8" /> Small</label>
<label><input type="radio" name="size" value="10" /> Medium</label>
<label><input type="radio" name="size" value="12" /> Large</label>
<label><input type="radio" name="size" value="14" checked/> Extra Large</label>
<input type="text" name="sz_tot" value="0.00" />
</p>
<h3>Pick Your Toppings</h3>
<p id="pizza_toppings">
<label><input type="checkbox" name="Pineapple" value="1.50" /> Pineapple</label>
<label><input type="checkbox" name="Onions" value="1.50" /> Onions </label>
<label><input type="checkbox" name="Ham" value="1.50" /> Ham</label>
<label><input type="checkbox" name="Sausage" value="1.50" /> Sausage</label>
<label><input type="checkbox" name="Pepperoni" value="1.50" /> Pepperoni</label>
<input type="text" name="tops_tot" value="0.00" />
</p>
<h3>Delivery Or Pick Up</h3>
<p>
<select class="delivery" id="pick_delivery" size="2">
<option value="0">Pick Up: Free</option>
<option value="2">Delivery: $2</option>
</select>
<input type="button" onclick="getDeliveryPrice()" id="delivery_pick" value="enter" /></button>
</p>
<p>
<label>Total: $ <input type="text" name="total" class="num" value="0.00" readonly="readonly" /></label>
</p>
<p>
<input type="button" value="Confirm" />
<input type="button" value="Cancel">
</p>
</fieldset>
</form>
<div>
<h2>Your Order:</h2>
<p>
<h4>Your Name: <span id="cust_name"> </span></h4>
<h4>Your Pizza Size:</h4>
<h4>Toppings Selected:</h4>
</p>
</div>
</fieldset>
</form>```
On the bottom of the page the results should look similar to this:
Your Name: Pam Love
Pizza Size Selected: Extra Large
Toppings Selected: Bacon, Pineapple, Ham
Total: 20.50
When clicked on confirm order, the onclick button should redirect the page to a new tab that says:
Your order will be ready in 20 minutes.
or if cancelled then the user clicks the cancel button also redirected to a new tab:
Your order is cancelled.
You can just use some css selectors to accomplish most of this.
Here is how you can get your selected size:
document.querySelector('input[type="radio"][name="size"]:checked').value
And here is how you can get the list of toppings:
[...document.querySelectorAll('input[type="checkbox"][name="topping"]:checked')].map((t) => t.value).join(', ')
The remaining things should be pretty easy to find using querySelector or getElementById

Limit Number of Checkboxes Checked

I have a form with several checkboxes. I have three categories of checkboxes in the form. I need to limit to a max of three checkboxes per category.
I used this script but it limits to three checkboxes per form.
jQuery(function(){
var max = 3;
var checkboxes = jQuery('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
How do I modify the above script to limit three checkboxes per category within one form?
HTML Example:
<!-- FORM CODE -->
<!-- Start Categories -->
<label>Cat 1</label>
<!-- Checkboxes for Cat 1 - Max of Three in Category -->
<input type="checkbox" value="Option 1" id="CAT_Custom_365571_0" name="CAT_Custom_365571" />Creative<br />
<input type="checkbox" value="Option 2" id="CAT_Custom_365571_1" name="CAT_Custom_365571" />Euphoric<br />
<input type="checkbox" value="Option 3" id="CAT_Custom_365571_2" name="CAT_Custom_365571" />Uplifted<br />
<!-- More checkboxes -->
<label>Cat 2</label>
<!-- Checkboxes for Cat 2 - Max of Three in Category -->
<input type="checkbox" value="Option 1" id="CAT_Custom_365572_0" name="CAT_Custom_365572" />Option 1<br />
<input type="checkbox" value="Option 2" id="CAT_Custom_365572_1" name="CAT_Custom_365572" />Option 2<br />
<input type="checkbox" value="Option 3" id="CAT_Custom_365572_2" name="CAT_Custom_365572" />Option 3<br />
<!-- More checkboxes -->
<label>Cat 3</label>
<!-- Checkboxes for Cat 3 - Max of Three in Category -->
<input type="checkbox" value="Option 1" id="CAT_Custom_365573_0" name="CAT_Custom_365573" />Option 1<br />
<input type="checkbox" value="Option 2" id="CAT_Custom_365573_1" name="CAT_Custom_365573" />Option 2<br />
<input type="checkbox" value="Option 3" id="CAT_Custom_365573_2" name="CAT_Custom_365573" />Option 3<br />
<!-- More checkboxes -->
<!-- MORE FORM CODE -->
Note: The CAT_Custom_365571_2 etc is generated by the CMS I use.
Try (if your markup matches the one in the fiddle)
jQuery(function(){
var max = 3;
var checkboxes = jQuery('input[type="checkbox"]');
checkboxes.click(function(){
var $this = $(this);
var set = $this.add($this.prevUntil('label')).add($this.nextUntil(':not(:checkbox)'));
var current = set.filter(':checked').length;
return current <= max;
});
});
Demo: Fiddle
Update:
Since you have a name for the checkboxes
jQuery(function(){
var max = 3;
var checkboxes = jQuery('input[type="checkbox"]');
checkboxes.click(function(){
var $this = $(this);
var set = checkboxes.filter('[name="'+ this.name +'"]')
var current = set.filter(':checked').length;
return current <= max;
});
});
Demo: Fiddle
jQUERY
$("input[name=chk]").change(function(){
var max= 3;
if( $("input[name=chk]:checked").length == max ){
$("input[name=chk]").attr('disabled', 'disabled');
$("input[name=chk]:checked").removeAttr('disabled');
}else{
$("input[name=chk]").removeAttr('disabled');
}
});
HTML
<input type="checkbox" name"chk" value="A"/>A
<input type="checkbox" name"chk" value="B"/>B
<input type="checkbox" name"chk" value="C"/>C
<input type="checkbox" name"chk" value="D"/>D
<input type="checkbox" name"chk" value="E"/>E
<input type="checkbox" name"chk" value="F"/>F
<input type="checkbox" name"chk" value="F"/>G
FIDDLE EXAMPLE IS HERE
Try this:
jQuery(function(){
var max = 3;
var categories = jQuery('label'); // use better selector for categories
categories.each(function(){
var checkboxes = $(this).find('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
});
just add a class to all the related check boxes, and just use the class selector when checking the checkboxes for a category.
eg:
HTML
<label>Cat 1</label>
<input type='checkbox' class='cat1' />
<input type='checkbox' class='cat1' />
<input type='checkbox' class='cat1' />
<label>Cat 2</label>
<input type='checkbox' class='cat2' />
<input type='checkbox' class='cat2' />
<input type='checkbox' class='cat2' />
...
JS
jQuery(function(){
var max = 3;
var cat1_checkboxes = jQuery('input.cat1[type="checkbox"]');
var cat2_checkboxes = jQuery('input.cat2[type="checkbox"]');
var cat3_checkboxes = jQuery('input.cat3[type="checkbox"]');
cat1_checkboxes.change(function(){
var current = cat1_checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
cat2_checkboxes.change(function(){
var current = cat2_checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
cat3_checkboxes.change(function(){
var current = cat3_checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
This is a newbie code with javascript. It's like working...hardly...
I call this function on each input.
But there is surely a way to call this function one time.
It's working but uncheking a random checkbox from thoses who call it.
<input type="checkBox" name="cat1" value="education" onClick="just2cat();">Education
<input type="checkBox" name="cat2" value="faith" onClick="just2cat();">Religions
<input type="checkBox" name="cat3" value="news" onClick="just2cat();">News
function just2cat()
{
var allInp = document.getElementsByTagName('input');
const MAX_CHECK_ = 2; /*How many checkbox could be checked*/
var nbChk =0;
for(var i= 0; i<allInp.length; i++)
{
if(allInp[i].type.toLowerCase()=='checkbox' && allInp[i].checked) /*OR
if(allInp[i].type.toLowerCase()=='checkbox' && allInp[i].checked===true) */
{
nbChk++;
if(nbChk > MAX_CHECK_)
{
alert("At most 2 categories can be chosen");
allInp[i].checked=false; /* try to Unchek the current checkbox :'( */
}
}
}
}

Checkbox value added by default

I'm attempting to make a code that will display the divs when checked and also add the values of the checkboxes together. I've managed to come up with this but now I want to make some of the checkboxes checked and their values added together by default. I can make the checkbox checked, however, I need the value to be added by default as well. Any help would be appreciated. Here is my code:
a
This is the first paragraph
This is the second paragraph
This is the third paragraph
<form name="formex">
<input onclick="clickCh(this) ; showPara()" class="classone" type="checkbox" name="one" value="10"> $10.00<br>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="two" value="12"> $12.00<br>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="three" value="1"> $1.00<br>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="four" value="2"> $2.00<br>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="five" value="24"> $24.00<br>
<br>
<input id="total" type="text" name="total">
</form>
My script
<script language="JavaScript" type="text/javascript">
var total = document.getElementById("total")
function clickCh(caller){
if(caller.checked){
add(caller)
} else {
subtract(caller)
}}
function add(caller){ total.value = total.value*1 + caller.value*1}
function subtract(caller){ total.value = total.value*1 - caller.value*1}
function showPara()
{
document.getElementById("first").style.display=(document.formex.one.checked) ? "inline" : "none";
document.getElementById("second").style.display=(document.formex.two.checked) ? "inline" : "none";
document.getElementById("third").style.display=(document.formex.three.checked) ? "inline" : "none";
return true;
}
</script>
jsFiddle: http://jsfiddle.net/TCZ6t/1/
You should be able to just add the attribute "checked" to the end of the tag to have it checked by default. In other words, if I wanted $10 to be checked by default I would just change the tag to:
<input checked onclick="clickCh(this) ; showPara()" class="classone" type="checkbox" name="one" value="10" checked> $10.00<br>
You could just loop all the checked checkboxes and call the add method like
var els = document.querySelectorAll('form[name="formex"] input[type="checkbox"]');
for (var i = 0; i < els.length; i++) {
if (els[i].checked) {
add(els[i])
}
}
Demo:
var total = document.getElementById("total");
function clickCh(caller) {
if (caller.checked) {
add(caller)
} else {
subtract(caller)
}
}
function add(caller) {
total.value = total.value * 1 + caller.value * 1
}
function subtract(caller) {
total.value = total.value * 1 - caller.value * 1
}
function showPara() {
document.getElementById("first").style.display = (document.formex.one.checked) ? "inline" : "none";
document.getElementById("second").style.display = (document.formex.two.checked) ? "inline" : "none";
document.getElementById("third").style.display = (document.formex.three.checked) ? "inline" : "none";
return true;
}
var els = document.querySelectorAll('form[name="formex"] input[type="checkbox"]');
for (var i = 0; i < els.length; i++) {
if (els[i].checked) {
add(els[i])
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="first" style="display:none;">This is the first paragraph</div> <br />
<div id="second" >This is the second paragraph</div> <br />
<div id="third" style="display:none;">This is the third paragraph</div> <br />
<form name="formex">
<input onclick="clickCh(this) ; showPara()" class="classone" type="checkbox" name="one" value="10"/> $10.00<br/>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="two" value="12"/> $12.00<br/>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="three" value="1"/> $1.00<br/>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="four" value="2" checked /> $2.00<br/>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="five" value="24" checked /> $24.00<br/>
<br/>
<input id="total" type="text" name="total"/>
</form>

Check random checkboxes using JQuery

I know how to check and uncheck particular checkbox with ID and CLASS.
But I want to randomly select 10 checkbox using Jquery.
I will have 100,40 or XX number of checkbox everytime. (HTML Checkbox)
It might be 100 checkbox or 50 checkbox or something else. It will be different everytime.
I want to check 10 checkboxes randomly when a button is pressed.
User can manually select those 10 checkboxes. Or they can just press the random button.
I am using Jquery.
$(':checkbox:checked').length;
But i want to find the length of all the checkboxes and i want to check 10 random checkbox.
Are you looking for something like this?
http://jsfiddle.net/qXwD9/
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
//Creating random numbers from an array
function getRandomArrayElements(arr, count) {
var randoms = [], clone = arr.slice(0);
for (var i = 0, index; i < count; ++i) {
index = Math.floor(Math.random() * clone.length);
randoms.push(clone[index]);
clone[index] = clone.pop();
}
return randoms;
}
//Dummy array
function createArray(c) {
var ar = [];
for (var i = 0; i < c; i++) {
ar.push(i);
}
return ar;
}
//check random checkboxes
function checkRandom(r, nodeList) {
for (var i = 0; i < r.length; i++) {
nodeList.get(r[i]).checked = true;
}
}
//console.log(getRandomArrayElements(a, 10));
$(function() {
var chkCount = 100;
//this can be changed
var numberOfChecked = 10;
//this can be changed
var docFrag = document.createElement("div");
for (var i = 0; i <= chkCount; i++) {
var chk = $("<input type='checkbox' />");
$(docFrag).append(chk);
}
$("#chkContainer").append(docFrag);
$("#btn").click(function(e) {
var chks = $('input[type=checkbox]');
chks.attr("checked", false);
var a = createArray(chkCount);
var r = getRandomArrayElements(a, numberOfChecked);
//console.log(r);
checkRandom(r, chks);
});
});
</script>
</head>
<body>
<div id="chkContainer"></div>
<div>
<input type="button" id="btn" value="click" />
</div>
</body>
How about this:
Working example: http://jsfiddle.net/MxGPR/23/
HTML:
<button>Press me</button>
<br/><br/>
<div class="checkboxes">
<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" />
<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" />
</div>
JAVASCRIPT (JQuery required):
$("button").click(function() {
// How many to be checked?
var must_check = 10;
// Count checkboxes
var checkboxes = $(".checkboxes input").size();
// Check random checkboxes until "must_check" limit reached
while ($(".checkboxes input:checked").size() < must_check) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * checkboxes) + 1;
// Check it
$(".checkboxes input:nth-child(" + random_checkbox + ")").prop("checked", true);
}
});

How to implement "select all" check box in HTML?

I have an HTML page with multiple checkboxes.
I need one more checkbox by the name "select all". When I select this checkbox all checkboxes in the HTML page must be selected. How can I do this?
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('foo');
for(var checkbox in checkboxes)
checkbox.checked = source.checked;
}
</script>
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
UPDATE:
The for each...in construct doesn't seem to work, at least in this case, in Safari 5 or Chrome 5. This code should work in all browsers:
function toggle(source) {
checkboxes = document.getElementsByName('foo');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
Using jQuery:
// Listen for click on toggle checkbox
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<input type="checkbox" name="checkbox-2" id="checkbox-2" />
<input type="checkbox" name="checkbox-3" id="checkbox-3" />
<!-- select all boxes -->
<input type="checkbox" name="select-all" id="select-all" />
I'm not sure anyone hasn't answered in this way (using jQuery):
$( '#container .toggle-button' ).click( function () {
$( '#container input[type="checkbox"]' ).prop('checked', this.checked)
})
It's clean, has no loops or if/else clauses and works as a charm.
I'm surprised no one mentioned document.querySelectorAll(). Pure JavaScript solution, works in IE9+.
function toggle(source) {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i] != source)
checkboxes[i].checked = source.checked;
}
}
<input type="checkbox" onclick="toggle(this);" />Check all?<br />
<input type="checkbox" />Bar 1<br />
<input type="checkbox" />Bar 2<br />
<input type="checkbox" />Bar 3<br />
<input type="checkbox" />Bar 4<br />
here's a different way less code
$(function () {
$('#select-all').click(function (event) {
var selected = this.checked;
// Iterate each checkbox
$(':checkbox').each(function () { this.checked = selected; });
});
});
Demo http://jsfiddle.net/H37cb/
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});
});
</script>
<div id="wrapper">
<li style="margin-top: 20px">
<input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
<ul>
<li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
<li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
<li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
<li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
</ul>
</li>
</ul>
<ul>
<li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
<li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
<li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
</ul>
</li>
</ul>
</li>
</div>
When you call document.getElementsByName("name"), you will get a Object. Use .item(index) to traverse all items of a Object
HTML:
<input type="checkbox" onclick="for(c in document.getElementsByName('rfile')) document.getElementsByName('rfile').item(c).checked = this.checked">
<input type=​"checkbox" name=​"rfile" value=​"/​cgi-bin/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​includes/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​misc/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​modules/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​profiles/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​scripts/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​sites/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​stats/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​themes/​">​
Slightly changed version which checks and unchecks respectfully
$('#select-all').click(function(event) {
var $that = $(this);
$(':checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
My simple solution allows to selectively select/deselect all checkboxes in a given portion of the form, while using different names for each checkbox, so that they can be easily recognized after the form is POSTed.
Javascript:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++) {
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
HTML example:
<p><input onClick="setAllCheckboxes('actors', this);" type="checkbox" />All of them</p>
<div id="actors">
<p><input type="checkbox" name="kevin" />Spacey, Kevin</p>
<p><input type="checkbox" name="colin" />Firth, Colin</p>
<p><input type="checkbox" name="scarlett" />Johansson, Scarlett</p>
</div>
I hope you like it!
<html>
<head>
<script type="text/javascript">
function do_this(){
var checkboxes = document.getElementsByName('approve[]');
var button = document.getElementById('toggle');
if(button.value == 'select'){
for (var i in checkboxes){
checkboxes[i].checked = 'FALSE';
}
button.value = 'deselect'
}else{
for (var i in checkboxes){
checkboxes[i].checked = '';
}
button.value = 'select';
}
}
</script>
</head>
<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />
<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>
</html>
Try this simple JQuery:
$('#select-all').click(function(event) {
if (this.checked) {
$(':checkbox').prop('checked', true);
} else {
$(':checkbox').prop('checked', false);
}
});
JavaScript is your best bet. The link below gives an example using buttons to de/select all. You could try to adapt it to use a check box, just use you 'select all' check box' onClick attribute.
Javascript Function to Check or Uncheck all Checkboxes
This page has a simpler example
http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html
This sample works with native JavaScript where the checkbox variable name varies, i.e. not all "foo."
<!DOCTYPE html>
<html>
<body>
<p>Toggling checkboxes</p>
<script>
function getcheckboxes() {
var node_list = document.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i < node_list.length; i++)
{
var node = node_list[i];
if (node.getAttribute('type') == 'checkbox')
{
checkboxes.push(node);
}
}
return checkboxes;
}
function toggle(source) {
checkboxes = getcheckboxes();
for (var i = 0 n = checkboxes.length; i < n; i++)
{
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" name="foo1" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo2" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo3" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo4" value="bar4"> Bar 4<br/>
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>
</body>
</html>
It's rather simple:
const selectAllCheckboxes = () => {
const checkboxes = document.querySelectorAll('input[type=checkbox]');
checkboxes.forEach((cb) => { cb.checked = true; });
}
If adopting the top answer for jQuery, remember that the object passed to the click function is an EventHandler, not the original checkbox object. Therefore code should be modified as follows.
HTML
<input type="checkbox" name="selectThemAll"/> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
Javascript
$(function() {
jQuery("[name=selectThemAll]").click(function(source) {
checkboxes = jQuery("[name=foo]");
for(var i in checkboxes){
checkboxes[i].checked = source.target.checked;
}
});
})
<asp:CheckBox ID="CheckBox1" runat="server" Text="Select All" onclick="checkAll(this);" />
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="Item 1">Item 1</asp:ListItem>
<asp:ListItem Value="Item 2">Item 2</asp:ListItem>
<asp:ListItem Value="Item 3">Item 3</asp:ListItem>
<asp:ListItem Value="Item 4">Item 4</asp:ListItem>
<asp:ListItem Value="Item 5">Item 5</asp:ListItem>
<asp:ListItem Value="Item 6">Item 6</asp:ListItem>
</asp:CheckBoxList>
<script type="text/javascript">
function checkAll(obj1) {
var checkboxCollection = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
checkboxCollection[i].checked = obj1.checked;
}
}
}
</script>
that should do the job done:
$(':checkbox').each(function() {
this.checked = true;
});
You may have different sets of checkboxes on the same form. Here is a solution that selects/unselects checkboxes by class name, using vanilla javascript function document.getElementsByClassName
The Select All button
<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All
Some of the checkboxes to select
<input type='checkbox' class='check_invoice' id='check_123' name='check_123' value='321' />
<input type='checkbox' class='check_invoice' id='check_456' name='check_456' value='852' />
The javascript
function selectAll() {
var blnChecked = document.getElementById("select_all_invoices").checked;
var check_invoices = document.getElementsByClassName("check_invoice");
var intLength = check_invoices.length;
for(var i = 0; i < intLength; i++) {
var check_invoice = check_invoices[i];
check_invoice.checked = blnChecked;
}
}
This is what this will do, for instance if you have 5 checkboxes, and you click check all,it check all, now if you uncheck all the checkbox probably by clicking each 5 checkboxs, by the time you uncheck the last checkbox, the select all checkbox also gets unchecked
$("#select-all").change(function(){
$(".allcheckbox").prop("checked", $(this).prop("checked"))
})
$(".allcheckbox").change(function(){
if($(this).prop("checked") == false){
$("#select-all").prop("checked", false)
}
if($(".allcheckbox:checked").length == $(".allcheckbox").length){
$("#select-all").prop("checked", true)
}
})
As I cannot comment, here as answer:
I would write Can Berk Güder's solution in a more general way,
so you may reuse the function for other checkboxes
<script language="JavaScript">
function toggleCheckboxes(source, cbName) {
checkboxes = document.getElementsByName(cbName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>
$(document).ready(function() {
$(document).on(' change', 'input[name="check_all"]', function() {
$('.cb').prop("checked", this.checked);
});
});
Using jQuery and knockout:
With this binding main checkbox stays in sync with underliying checkboxes, it will be unchecked unless all checkboxes checked.
ko.bindingHandlers.allChecked = {
init: function (element, valueAccessor) {
var selector = valueAccessor();
function getChecked () {
element.checked = $(selector).toArray().every(function (checkbox) {
return checkbox.checked;
});
}
function setChecked (value) {
$(selector).toArray().forEach(function (checkbox) {
if (checkbox.checked !== value) {
checkbox.click();
}
});
}
ko.utils.registerEventHandler(element, 'click', function (event) {
setChecked(event.target.checked);
});
$(window.document).on('change', selector, getChecked);
ko.utils.domNodeDisposal.addDisposeCallback(element, () => {
$(window.document).off('change', selector, getChecked);
});
getChecked();
}
};
in html:
<input id="check-all-values" type="checkbox" data-bind="allChecked: '.checkValue'"/>
<input id="check-1" type="checkbox" class="checkValue"/>
<input id="check-2" type="checkbox" class="checkValue"/>
to make it in short-hand version by using jQuery
The select all checkbox
<input type="checkbox" id="chkSelectAll">
The children checkbox
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
jQuery
$("#chkSelectAll").on('click', function(){
this.checked ? $(".chkDel").prop("checked",true) : $(".chkDel").prop("checked",false);
})
Below methods are very Easy to understand and you can implement existing forms in minutes
With Jquery,
$(document).ready(function() {
$('#check-all').click(function(){
$("input:checkbox").attr('checked', true);
});
$('#uncheck-all').click(function(){
$("input:checkbox").attr('checked', false);
});
});
in HTML form put below buttons
<a id="check-all" href="javascript:void(0);">check all</a>
<a id="uncheck-all" href="javascript:void(0);">uncheck all</a>
With just using javascript,
<script type="text/javascript">
function checkAll(formname, checktoggle)
{
var checkboxes = new Array();
checkboxes = document[formname].getElementsByTagName('input');
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = checktoggle;
}
}
}
</script>
in HTML form put below buttons
<button onclick="javascript:checkAll('form3', true);" href="javascript:void();">check all</button>
<button onclick="javascript:checkAll('form3', false);" href="javascript:void();">uncheck all</button>
Here is a backbone.js implementation:
events: {
"click #toggleChecked" : "toggleChecked"
},
toggleChecked: function(event) {
var checkboxes = document.getElementsByName('options');
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].checked = event.currentTarget.checked;
}
},
html
<input class='all' type='checkbox'> All
<input class='item' type='checkbox' value='1'> 1
<input class='item' type='checkbox' value='2'> 2
<input class='item' type='checkbox' value='3'> 3
javascript
$(':checkbox.all').change(function(){
$(':checkbox.item').prop('checked', this.checked);
});
1: Add the onchange event Handler
<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>
2: Modify the code to handle checked/unchecked
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
You can Use This code.
var checkbox = document.getElementById("dlCheckAll4Delete");
checkbox.addEventListener("click", function (event) {
let checkboxes = document.querySelectorAll(".dlMultiDelete");
checkboxes.forEach(function (ele) {
ele.checked = !!checkbox.checked;
});
});
You can use this simple code
$('.checkall').click(function(){
var checked = $(this).prop('checked');
$('.checkme').prop('checked', checked);
});
Maybe a bit late, but when dealing with a check all checkbox, I believe you should also handle the scenario for when you have the check all checkbox checked, and then unchecking one of the checkboxes below.
In that case it should automatically uncheck the check all checkbox.
Also when manually checking all the checkboxes, you should end up with the check all checkbox being automatically checked.
You need two event handlers, one for the check all box, and one for when clicking any of the single boxes below.
// HANDLES THE INDIVIDUAL CHECKBOX CLICKS
function client_onclick() {
var selectAllChecked = $("#chk-clients-all").prop("checked");
// IF CHECK ALL IS CHECKED, AND YOU'RE UNCHECKING AN INDIVIDUAL BOX, JUST UNCHECK THE CHECK ALL CHECKBOX.
if (selectAllChecked && $(this).prop("checked") == false) {
$("#chk-clients-all").prop("checked", false);
} else { // OTHERWISE WE NEED TO LOOP THROUGH INDIVIDUAL CHECKBOXES AND SEE IF THEY ARE ALL CHECKED, THEN CHECK THE SELECT ALL CHECKBOX ACCORDINGLY.
var allChecked = true;
$(".client").each(function () {
allChecked = $(this).prop("checked");
if (!allChecked) {
return false;
}
});
$("#chk-clients-all").prop("checked", allChecked);
}
}
// HANDLES THE TOP CHECK ALL CHECKBOX
function client_all_onclick() {
$(".client").prop("checked", $(this).prop("checked"));
}

Categories