array of checkbox value checked and unchecked - javascript

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array.
this is the function:
$(document).ready(function () {
$('input[type="checkbox"]').change(function () {
var mycheck = new Array();
if ($(this).is(':checked')) {
$("#line-checkbox-1:checked").each(function () {
mycheck.push($(this).val());//aggiungo value del checked
});
alert(mycheck)
} else {
var itemtoRemove = $(this);
mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked
alert(mycheck);
}
});
This is HTML of the checkbox:
<div class="col-lg-3">
<input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">
</div>

Try This Simple Script, this works for you:
HTML
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
JQUERY
$(document).ready(function ()
{
$('input[type="checkbox"]').change(function ()
{
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
alert(arr);
});
});

Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. you should recheck the list everytime a checkbox is changed. That means you dont need that if.( if($(this).is(":checked") )
$('.checkboxes input[type="checkbox"]').change(function () {
var mycheck = new Array();
$(".checkboxes input[type='checkbox']:checked").each(function () {
if ($(this).is(':checked')) {
mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
}
});
alert(mycheck);
});
here is a fiddle if i understand correctly what you are trying to do

Related

For each input if they are changed to checked store input ID of checked input in variable

I would like to store the ID of the input that is currently checked in variable selectedLevelId.
$("[id^=level_]").each(function() {
$(this).change(function() {
if ($(this).is(':checked')) {
var selectedLevelId = $(this).prop('id');
}
});
});
document.getElementById('levelVal').innerHTML=selectedLevelId;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="level_4432" name="level_id" type="radio" value="4432">
<input id="level_4235" name="level_id" type="radio" value="4235">
<input id="level_1454" name="level_id" type="radio" value="1454">
<input id="level_9823" name="level_id" type="radio" value="9823">
<div id="levelVal">
</div>
You have the output of your logic outside the .change() event so JS doesn't know what's happening inside the event. Just put the logic inside and it will work:
var selectedLevelId;
$("[id^=level_]").each(function() {
$(this).change(function() {
if ($(this).is(':checked')) {
selectedLevelId = $(this).prop('id');
document.getElementById('levelVal').innerHTML = selectedLevelId;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="level_4432" name="level_id" type="radio" value="4432">
<input id="level_4235" name="level_id" type="radio" value="4235">
<input id="level_1454" name="level_id" type="radio" value="1454">
<input id="level_9823" name="level_id" type="radio" value="9823">
<div id="levelVal">
</div>
There are 2 solutions
1 - change it inside the on change event
2 - create an interval that checks for new value every "n" ms
// 1-
/*let selectedLevelId;
$("[id^=level_]").each(function() {
$(this).change(function() {
if ($(this).is(':checked')) {
document.getElementById('levelVal').innerHTML = $(this).prop('id');
}
});
});
*/
// OR
// 2-
let selectedLevelId;
$("[id^=level_]").each(function() {
$(this).change(function() {
if ($(this).is(':checked')) {
selectedLevelId = $(this).prop('id');
}
});
});
setInterval(function(){
document.getElementById('levelVal').innerHTML = selectedLevelId;
}, 100);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="level_4432" name="level_id" type="radio" value="4432">
<input id="level_4235" name="level_id" type="radio" value="4235">
<input id="level_1454" name="level_id" type="radio" value="1454">
<input id="level_9823" name="level_id" type="radio" value="9823">
<div id="levelVal">
</div>

Call javascript function when specific radio become unselected

I have some radio inputs and I would like to call a JS function only in the case where the id3 radio is selected and becomes unselected.
I searched, but I found only solutions, where only checked/unchecked status is checked:
$("input:radio").change(function() {
if ($("#id3").is(":checked")) {
alert('checked');
} else {
alert('unchecked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5" class="">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5" class="">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5" class="">
You will need to keep track of when you last clicked it, to see if you need to say that it was unselected.
Plain JS
This is fairly simple to do in pure JavaScript. You can utilize the data-* attribute design to store the state of when an element was last checked.
let targetEl = document.getElementById('id3');
Array.from(document.querySelectorAll('input[type="radio"]')).forEach(radioEl => {
radioEl.addEventListener('change', function(e) {
if (e.target.id === targetEl.id && e.target.checked) {
alert(e.target.id + ' - checked');
e.target.setAttribute('data-waschecked', true);
} else if (targetEl.getAttribute('data-waschecked') === 'true') {
alert(targetEl.id + ' - unchecked');
targetEl.setAttribute('data-waschecked', false);
}
});
});
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">
jQuery
This advanced solution allows you to monitor multiple radio buttons. It is written mostly in jQuery.
const trackableIds = [ 'id1', 'id3' ];
$('input[type="radio"]').on('change', function(e) {
let $target = $(e.target),
isTrackable = trackableIds.includes($target.attr('id'));
if (isTrackable && $target.is(':checked')) {
alert($target.attr('id') + ' - checked');
$target.attr('data-waschecked', true);
}
trackableIds.filter(trackId => trackId !== $target.attr('id'))
.forEach(trackId => {
let $trackable = $('#' + trackId);
if ($trackable.attr('data-waschecked') === 'true') {
alert($trackable.attr('id') + ' - unchecked');
$trackable.attr('data-waschecked', false);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">
As a jQuery plugin
Nearly identical behavior to the jQuery above, but as a plugin. There are even custom callback function options for checking/unchecking.
(($) => {
$.fn.trackRadio = function(ids, opts) {
this.on('change', function(e) {
let $target = $(e.target), isTrackable = ids.includes($target.attr('id'));
if (isTrackable && $target.is(':checked')) {
opts.onCheckFn($target);
$target.attr('data-waschecked', true);
}
ids.filter(trackId => trackId !== $target.attr('id')).forEach(trackId => {
let $trackable = $('#' + trackId);
if ($trackable.attr('data-waschecked') === 'true') {
opts.onCheckFn($trackable);
$trackable.attr('data-waschecked', false);
}
});
});
}
})(jQuery);
$('input[type="radio"]').trackRadio(['id1', 'id3'], {
onCheckFn : function($radio) {
alert($radio.attr('id') + ' - checked');
},
onUncheckFn : function($radio) {
alert($radio.attr('id') + ' - unchecked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">
What you can do is add a watcher variable to find out whether you are deselecting the radio button.
var isChecked = false;
$("input:radio").change(function () {
if ($("#id3").is(":checked")) {
isChecked = true;
} else {
if (isChecked) {
alert("Unchecked");
isChecked = false;
}
}
});
CodePen: https://codepen.io/ashfaq_haq/pen/LYYjLrv?editors=1010

Get the values of column if checkbox/radio box is checked

I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>

checkbox - Check uncheck functionality is not working

My situation :
I am working on an shopping cart application and it contains some filters:
Filter by color (checkboxes)
Filter by style (checkboxes)
on selecting some of the colors my url becomes like this:
http://example.com/women/try.php?color=10,11,12,13
My issue :
On unchecking some colors the related params are not getting cleared from the url.
Also when I select some styles , I want the url to be like this:
http://example.com/women/try.php?color=10,11,12,13&style=1,2,3
Please help me how to achieve this functionality.
My code :
<?php
$colors = $_GET['color'];
$sel_colors = explode(',', $colors);
foreach($sel_colors as $k=>$v) {
$c['check'][$v] = $v;
}
for($i=10;$i<=14;$i++) { ?>
<input type="checkbox" name="color[]" value="<?php echo $i; ?>" <?php echo $check_value = ($c['check'][$i]) ? 'checked' : '0'; ?> >
<label>Color #<?php echo $i.'--'.$check_value; ?></label><?php
}
?><br/><br/><br/>
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" >
<label>style #2</label>
<input type="checkbox" name="type" value="3" >
<label>style #3</label>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js" ></script>
<script type="text/javascript">
var baseUrl = 'http://website/women/try.php?color=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ',' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
</script>
Here is a code snippet of working solution. Name of the color checkbox is changed from color[] to just color
var baseUrl = 'http://website/women/try.php?';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
//Get all the selected color values
var queryString = "color="+$('[name="color"]:checked')
.map(function() {return this.value;}).get().join(',');
//Append all the selected styles
queryString += "&style="+$('[name="type"]:checked').map(function() {return this.value;}).get().join(',');
//reload page - commented for this snippet
//window.location = baseUrl + queryString;
alert(baseUrl + queryString);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Color filter -->
<input type="checkbox" name="color" value="1" checked >
<label>Color 1</label>
<input type="checkbox" name="color" value="2" checked >
<label>Color 2</label>
<input type="checkbox" name="color" value="3" checked >
<label>Color 3</label>
<input type="checkbox" name="color" value="4" checked >
<label>Color 4</label>
<BR><BR>
<!-- Style filter -->
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" checked>
<label>style #2</label>
<input type="checkbox" name="type" value="3" checked>
<label>style #3</label>
Use map() function to get all checked color and style checkbox values like following.
var baseUrl = 'http://website/women/try.php?color=';
$('input[name="color[]"], input[name="type"]').change(function () {
var colors = $('input[name="color[]"]:checked').map(function () { return this.value; }).get().join();
var styles = $('input[name="type"]:checked').map(function () { return this.value; }).get().join();
window.location = baseUrl + colors + '&style=' + styles;
});

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