check all checkboxes javascript - javascript

I'm trying to have all checkboxes checked (true) when the user clicks on "All" button. I tried this, firstly just to see if "Anglais" could be checked clicking on "All" :
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll()" name="all" id="all" value="Tous" /> Tous
My Javascript :
function checkedAll () {
var checked = false;
var all = document.getElementById('all');
if (checked == false) {
checked = true
}
else {
checked = false
}
var ang = document.getElementById('anglais').checked
if (ang == true) {
ang.checked = true;
}
But the button(s) are not checked when I click on All. I think I don't understand exactly how to use the .checked method..
Maybe, some of my code has not logic, because it was from this example :
https://www.hscripts.com/scripts/JavaScript/select-all-checkbox.php

Couple modifications:
Pass in the all checkbox to the checkedAll method (this allows you to reference it without having to re-find it).
Used document.getElementsByTagName to find the other checkboxes, but you could just as easily use document.getElementById for each one (anglais, allemand, etc.)
Set every other checkbox's checked status to the all.checked value. No need for a true/false comparison.
function checkedAll(allCheckbox){
var allCheckboxes = document.getElementsByTagName('input');
for (var i = 0; i < allCheckboxes.length; i++){
var curCheckbox = allCheckboxes[i];
if (curCheckbox.id != 'all'){
curCheckbox.checked = allCheckbox.checked;
}
}
}
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll(this)" name="all" id="all" value="Tous" /> Tous
The more explicit way would be:
function checkedAll(){
var isAllChecked = document.getElementById('all').checked;
// Set the other checkboxes .checked property based on the
// .checked status of the `all` checkbox
document.getElementById('anglais').checked = isAllChecked;
document.getElementById('allemand').checked = isAllChecked;
document.getElementById('espagnol').checked = isAllChecked;
document.getElementById('francais').checked = isAllChecked;
}
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll()" name="all" id="all" value="Tous" /> Tous

Related

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" />

Javascript not updating hidden field correctly

The Javascript code below should update the value of a hidden field which has the ID=adjustChk to 'y' if any of the radio buttons are selected as Yes.
It updates the field as expected, but if any of the radios are changed back to 'n' the hidden field is also updated to 'n'. Hoped the break would exit the for loop when a 'y' was encountered, but this doesn't behave the way I'd hoped.
window.onload = function() {
var ele = document.getElementsByTagName("input");
var hid = document.getElementById("adjustChk");
var chkItm = "";
for(var i = 0, item; item = ele[i]; i++){
item.addEventListener("click", function() {
chkItm = this.value;
for (var i = 0; i < ele.length; i++){
if(chkItm === 'y'){
hid.value = 'y';
break;
} else {
hid.value = 'n';
}
};
});
};
};
<div>
Yes<input type="radio" name="radio1" value="y" />
No<input type="radio" name="radio1" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio2" value="y" />
No<input type="radio" name="radio2" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio3" value="y" />
No<input type="radio" name="radio3" value="n" checked="checked" />
</div>
<input id="adjustChk" type="hidden" value="n" />
I'm still getting the hang of JS, so if there is also a better way using plain Jasvascript it would be helpful to see it!
The problem is that you're looking at the value of the radio button that was clicked, but what you really want is to look at the checked state of all of the "yes" radio buttons instead.
I'd probably get a true array of elements (using the slice trick described in the "array-like" part of this answer), use Array#forEach to hook up the handler (but the for loop is fine too), and when processing a click, use Array#some to get a flag for whether any of the buttons that's checked has value "y".
Here's an example, see the comments; I made the hidden field visible so it was easy to see its value at any given time:
// Get the radio buttons, convert the NodeList into a true array
var ele = Array.prototype.slice.call(document.getElementsByTagName("input"));
// Get the hidden field
var hid = document.getElementById("adjustChk");
// Attach a handler to all of our radio buttons
ele.forEach(function(el) {
el.addEventListener("click", radioHandler, false);
});
function radioHandler() {
// Set `hid.value` to "y" if any of the checked checkboxes have the value "y",
// "n" otherwise
hid.value = ele.some(function(el) {
return el.checked && el.value === "y";
}) ? "y" : "n";
}
<div>
Yes<input type="radio" name="radio1" value="y" />
No<input type="radio" name="radio1" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio2" value="y" />
No<input type="radio" name="radio2" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio3" value="y" />
No<input type="radio" name="radio3" value="n" checked="checked" />
</div>
<input id="adjustChk" type="text" value="n" />
But, here's a version using for loops instead:
// Get the radio buttons
var ele = document.getElementsByTagName("input");
// Get the hidden field
var hid = document.getElementById("adjustChk");
// Attach a handler to all of our radio buttons
for (var i = 0; i < ele.length; ++i) {
ele[i].addEventListener("click", radioHandler, false);
}
function radioHandler() {
// Assume no "yes" radio buttons are checked
hid.value = "n";
for (var i = 0; i < ele.length; ++i) {
// Get the radio button for this loop iteration
var el = ele[i];
// If it's checked and has value "y", update the value and we're done
if (el.checked && el.value === "y") {
hid.value = "y";
break;
}
}
}
<div>
Yes<input type="radio" name="radio1" value="y" />
No<input type="radio" name="radio1" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio2" value="y" />
No<input type="radio" name="radio2" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio3" value="y" />
No<input type="radio" name="radio3" value="n" checked="checked" />
</div>
<input id="adjustChk" type="text" value="n" />
Just for fun, here's that first example using ES2015 (aka "ES6"):
// Get the radio buttons as a true array
let ele = Array.from(document.getElementsByTagName("input"));
// Get the hidden field
let hid = document.getElementById("adjustChk");
// Attach a handler to all of our radio buttons
ele.forEach(el => {
el.addEventListener("click", radioHandler, false);
});
function radioHandler() {
// Set `hid.value` to "y" if any of the checked checkboxes have the value "y",
// "n" otherwise
hid.value = ele.some(el => el.checked && el.value === "y") ? "y" : "n";
}
<div>
Yes<input type="radio" name="radio1" value="y" />
No<input type="radio" name="radio1" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio2" value="y" />
No<input type="radio" name="radio2" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio3" value="y" />
No<input type="radio" name="radio3" value="n" checked="checked" />
</div>
<input id="adjustChk" type="text" value="n" />

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')
});
});
});

jquery: how to check if all radio buttons in a div are selected

my html looks like this
<div id="div1">
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
radio buttons are dynamically generated on my html so in that div i don't know how many radio buttons i have.
i want to make sure that the user will select a value for each one of them before he submits the form, how can i check that all radio buttons inside my div has a value checked?
Thank you
$(":radio").change(function() {
var names = {};
$(':radio').each(function() {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function() {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
Demo: http://jsfiddle.net/yFaAj/15/
Restructure your HTML slightly - wrap each radio group in (say) a div. Then you can just do something like this to validate the form when the user submits it:
if ($('div:not(:has(:radio:checked))').length) {
alert("At least one group is blank");
}
Of course this can be tweaked in various ways to suit your HTML. The idea was from Find all radio groups which haven't been selected
Solution here http://jsfiddle.net/QxdnZ/1/
var checked = $("#div1 :radio:checked");
var groups = [];
$("#div1 :radio").each(function() {
if (groups.indexOf(this.name) < 0) {
groups.push(this.name);
}
});
if (groups.length == checked.length) {
alert('all are checked!');
}
else {
var total = groups.length - checked.length;
var a = total>1?' groups are ':' group is ';
alert(total + a + 'not selected');
}
Validate the form when the user submits it, using this validation code.
var blank = false;
$("input:radio").each(function() {
var val = $('input:radio[name=' + this.name + ']:checked').val();
if (val === undefined) {
blank = true;
return false;
}
});
alert(blank ? "At least one group is blank" : "All groups are checked");
First we get the names of all the radio button groups, then check that each one has a value. (Actually we're doing multiple checks, but that doesn't really matter.)
Looking for something along these lines? http://jsfiddle.net/gXsZp/3/
<div id="div1">
Q1
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<br/>Q2
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<br/>Q3
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
<br/>
<input id="btn" type="submit" text="submit"/>
$('#btn').click(function(){
if ( $('#div1 input:radio:checked').size() == 3 )
return true;
return false;
});
Try this one:
$('input:radio', $('#div1')).each(function() {
if(name && name == $(this).attr('name'))
return true; // Skip when checking the same element name.
name = $(this).attr('name');
if(! $('input:radio[name="' + name + '"]:checked').length) {
alert('Oops, you missed some input there.. [' + name + ']');
return false;
}
});
It will loop through every radio button to check for checked radio & will break as soon it found non-checked radio group (first error found). But if you prefer to get all the errors (not only the first error found), just remove return false.
Try this:
function check(){
var allCheck = true;
if($("#div1 :radio:checked").length==0){
allCheck=false;
}
$("#div1 :radio").each(function(){
for(var i=0;i<$("#div1 :radio:checked").length;i++)
if($(this).attr("name")===$($("#div1 :radio:checked")[i]).attr("name"))
break;
else if(i==$("#div1 :radio:checked").length-1)
allCheck = false;
});
return allCheck;
}
This will work:
if($("#div1").children("input:radio:checked").size() == 3)
{
alert('three inputs were checked');
}

Making "Mark all" button

How can i make a "Mark all" link that, marks all checkboxes there is inside a td:
<td style="padding-right:4px;padding:4px;" class="alternating">
<input name="cbPick" type="checkbox" value="88156144" />
</td>
Don't know what language you write this in.. JavaScript?
It would be in Javascript.
You would be using the DOM API.
function markAll() {
var tds = document.getElementsByTagName('td');
for(var index in tds) {
var innerNode = tds[index].firstChild;
if(innerNode.tagName == 'input' && innerNode.attributes.type="checkbox")
innerNode.checked = true;
}
}
You'd then need to make sure that the onClicked handler for the mark all link references this function. This code also assumes that where the tickbox is inside the TD's, it is the first child - otherwise this code would be more complicated.
Reference info:
http://www.w3schools.com/jsref/dom_obj_checkbox.asp
Code:
function checkAll(value, arr) {
$(arr).each(function () {
if (value) {
$(this).attr('checked', 'checked');
}
else {
$(this).removeAttr('checked');
}
});
}
Usage:
<input type="checkbox" class="check' /><br />
<input type="checkbox" class="check' /><br />
<input type="checkbox" class="check' /><br />
Mark all
P.S.
Yes, it requires jQuery. OMG OMG!!
Yes, that would be javascript, something like:
<script type="text/javascript">
function selectAll(x) {
for(var i=0,l=x.form.length; i<l; i++){
if(x.form[i].type == 'checkbox' && x.form[i].name != 'selectAll'){
x.form[i].checked=x.form[i].checked?false:true
}
}
}
</script>
<form>
<input type="checkbox" name="selectAll" onclick="selectAll(this)" /> (Select all)<br />
<input type="checkbox" name="a" /> (A)<br />
<input type="checkbox" name="b" /> (B)<br />
<input type="checkbox" name="c" /> (C)<br />
<input type="checkbox" name="d" /> (D)<br />
<input type="checkbox" name="e" /> (E)
</form>
Yeah javascript is the way to go
here is a link for a way to do it
http://www.shiningstar.net/articles/articles/javascript/checkboxes.asp

Categories

Resources