How to get all checked checkboxes - javascript

I have a set of input checkboxes with the same name
and I would like to determine which checkboxes have been checked using javascript, how can I achieve that?
I know only how to get all the checkboxes as follows:
var checkboxes = document.getElementsByName('mycheckboxes');

In IE9+, Chrome or Firefox you can do:
var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

A simple for loop which tests the checked property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked further if needed.
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");

For a simple two- (or one) liner this code can be:
checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);
Here the Array.prototype.slice.call() part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value) on the end of line 2.
The => is javascript's arrow function notation.

Get all the checked checkbox value in an array - one liner
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);
console.log(data);
<div class="row">
<input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1">
<label class="custom-control-label" for="inlineCheckbox1">Option1</label>
<input class="custom-control-input inp" type="checkbox" id="inlineCheckbox1" value="option2">
<label class="custom-control-label" for="inlineCheckbox1">Option2</label>
<input class="custom-control-input inp" Checked type="checkbox" id="inlineCheckbox1" value="option3">
<label class="custom-control-label" for="inlineCheckbox1">Option3</label>
</div>

You can just give a class for all checkboxes in the form, and get their checked property like this:
document.querySelectorAll('.mycheckbox').forEach(function(elem) {
console.log(elem.checked);
});
<div>
<label><input type="checkbox" name="mycheckbox[]" class="mycheckbox" value="1" checked="checked">Johnson</label>
</div>
<div>
<label><input type="checkbox" name="mycheckbox[]" class="mycheckbox" value="2">
Henry</label>
</div>
<div>
<label><input type="checkbox" name="mycheckbox[]" class="mycheckbox" value="3" checked="checked">
Donald</label>
</div>

$(document).ready(function () {
// Single check Box Checked
$(document).on("change", ".check_class", function () {
$(".check_class").prop("checked", false);
$(this).prop("checked", true);
var value = $(this).val();
console.log("Device Serial No is = " + value)
});
//get all emp Selected
$(document).on("click", "#EmpUpload", function (evnt) {
var emp =[]
const data = [...document.querySelectorAll('.EmpID:checked')].map(e => e.value);
emp.push(data)
console.log("Selected Emp Here [] = " + emp);
});
});
<!DOCTYPE html>
<html>
<head>
<title>Employee CheckBox Data Sample </title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid w-75 pt-5">
<div class="row border-top">
<div class="col-md-12">
<button type="button" class="btn btn-success float-right" id="EmpUpload">Get On Click</button>
</div>
<div class="col-md-4 border-right">
<table id="example" class="display w-100">
<thead>
<tr>
<th>#</th>
<th>Device</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="check_class" value="990099" name="serialNo" /></td>
<td>Office</td>
<td>Delhi</td>
</tr>
<tr>
<td><input type="checkbox" class="check_class" value="778899" name="serialNo" /></td>
<td>Garrett</td>
<td>Accountant</td>
</tr>
</tfoot>
</table>
</div>
<div class="col-md-8">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>#</th>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="EmpID" value="1001" name="serialNo" /></td>
<td>1001</td>
<td>Shaqubi Hassan</td>
</tr>
<tr>
<td><input type="checkbox" class="EmpID" value="1002" name="serialNo" /></td>
<td>1002</td>
<td>Balwinder Singh</td>
</tr>
<tr>
<td><input type="checkbox" class="EmpID" value="1003" name="serialNo" /></td>
<td>1003</td>
<td>Balwinder Singh</td>
</tr>
<tr>
<td><input type="checkbox" class="EmpID" value="1004" name="serialNo" /></td>
<td>1004</td>
<td>Singh</td>
</tr>
<tr>
<td><input type="checkbox" class="EmpID" value="1005" name="serialNo" /></td>
<td>1005</td>
<td>Sohi</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>

if you are using the <form> element you can take advantage of the form event using :
function onSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
console.log(data.getAll("mycheckboxs")) // will print only checked inputs
}
<form onsubmit="onSubmit(event)">
<label for="checkbox1">
Checkbox 1
<input id="checkbox1" name="mycheckboxs" type="checkbox" checked="true" value="1"/>
</label><br/>
<label for="checkbox2">
Checkbox 2
<input id="checkbox2" name="mycheckboxs" type="checkbox" value="2"/>
</label><br/>
<label for="checkbox3">
Checkbox 3
<input id="checkbox3" name="mycheckboxs" type="checkbox" value="3"/>
</label><br/>
<label for="checkbox4">
Checkbox 4
<input id="checkbox4" name="mycheckboxs" type="checkbox" checked="true" value="4"/>
</label><br/>
<div>
<br/>
<button type="submit">Submit</button>
</div>
</form>
Good luck!!

Related

How to check all checkboxes with different names in the same row

I Have html table as below code, How to check all checkboxes with different names in the same row??
Such as in the row of "Item name 1": if I check the box of "Check all", and then the box of "Date of Start: 2022-04-01" and the box of " Date of End: 2022-04-30" will be auto checked.
<table border="1" cellpadding="10" cellspacing="1" width="100%" class="tblListForm">
<tbody><tr class="listheader">
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('tbid[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<td style="width:10%"><input type="checkbox" onclick="toggle(this)">Quantity/Select All</td>
<td style="width:67%"> Item Details </td>
<td style="width:10%; text-align:right;"> Unit Price </td>
<td style="width:13%; text-align:right;"> Sub-total </td>
</tr>
<tr class="evenRow">
<td style="vertical-align:top">
<input type="checkbox" name="tbid[]" value="238"> 1</td>
<td style="vertical-align:top">
Item name 1 <br>
<input type="checkbox" name="item_no[]" value="1"> Check all<input type="checkbox" name="item_date_start[]" value="2022-04-01">Date of Start: 2022-04-01<input type="checkbox" name="item_date_end[]" value="2022-04-30"> Date of End: 2022-04-30</td>
<td style="vertical-align:top; text-align:right;">
105.00</td>
<td style="vertical-align:top; text-align:right;">
105.00</td>
</tr>
<tr class="oddRow">
<td style="vertical-align:top">
<input type="checkbox" name="tbid[]" value="239"> 1</td>
<td style="vertical-align:top">
Item name 2<br>
<input type="checkbox" name="item_no[]" value="17"> Check all<input type="checkbox" name="item_date_start[]" value="2022-05-01">Date of Start: 2022-05-01<input type="checkbox" name="item_date_end[]" value="2022-05-31"> Date of End: 2022-05-31</td>
<td style="vertical-align:top; text-align:right;">
250.00</td>
<td style="vertical-align:top; text-align:right;">
250.00</td>
</tr>
<tr class="listheader">
<td></td>
<td></td>
<td style="vertical-align:top; text-align:right;"> Total (HKD): </td>
<td style="vertical-align:top; text-align:right;"> 355.00</td>
</tr>
</tbody>
</table>
Thank you very much for your sharing & support in advance!
In this example I added a <fieldset> as a (near) parent to the checkboxes. The event listener will look for any change in the form. In the if() statement I determine if it was a "Check all" that changed. If so, all the input elements in the closest fieldset should have the same value.
document.forms.form01.addEventListener('change', e => {
// the field that just changed
let field = e.target;
// somehow determine if the change was
// on a "Check all" field -- here if class name = "checkall"
if (field.className == 'checkall') {
// get the parent fieldset
let fieldset = e.target.closest('fieldset');
// for each element in fieldset
[...fieldset.elements].forEach(input => {
// all should have the same value as "check all"
input.checked = field.checked;
});
}
});
<form name="form01">
<table>
<tr>
<td style="vertical-align:top">
<fieldset>
<label><input type="checkbox" name="item_no[]" class="checkall" value="1">Check all</label>
<label><input type="checkbox" name="item_date_start[]" value="2022-04-01">Date of Start: 2022-04-01</label>
<label><input type="checkbox" name="item_date_end[]" value="2022-04-30"> Date of End: 2022-04-30</label>
</fieldset>
</td>
</tr>
</table>
</form>
I find a similar answer from the web as below, but how to remove checkbox if click Uncheck, need to rewrite the javascript.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
type="text/javascript"
src="//code.jquery.com/jquery-1.9.1.js"
></script>
</head>
<body>
<div id="div1">
<input type="button" id="btnDiv1" class="select-all" value="Check / Uncheck" />
<input type="checkbox" class="check" />Mark
<input type="checkbox" class="check" />Frank</div>
<div id="div2">
<input type="button" id="btnDiv2" class="select-all" value="Check / Uncheck" />
<input type="checkbox" class="check" />John
<input type="checkbox" class="check" />Travis
<input type="checkbox" class="check" />Matt</div>
<div id="div3">
<input type="button" id="btnDiv3" class="select-all" value="Check / Uncheck" />
<input type="checkbox" class="check" />Lee
<input type="checkbox" class="check" />Charles</div>
<script type="text/javascript">
$('.select-all').on('click', function ()
{
$(this).nextAll('.check').prop('checked', true);
});
</script>
</body>
</html>

jquery returns last changed checkbox on bulk check/uncheck

I am trying to get data-region-code attribute from all the checkbox that were changed (checked/unchecked). But with my code, I am getting the last changed checkbox, not all the checkboxes. For eg: If I'm changing checkbox for data-region-code 001, 002, 003, 004, I will get the value as 004 as it is the last changed checkbox.
For reference: when checkbox is changed, I add class=changed for input.
Structure (I have more tr, maybe around 18-20 with same structure):
<table class= settings-container">
<thead></thead>
<tbody>
<tr id="">
<td></td>
<td></td>
<td>
<input type="checkbox" name="blockage_simulation[]" data-region-code="001" id="blockage_simulation" checked="" class="changed">
</td>
</tr>
<tr id="">
<td></td>
<td></td>
<td>
<input type="checkbox" name="blockage_simulation[]" data-region-code="002" id="blockage_simulation" class="changed">
</td>
</tr>
</tbody>
</table>
Code:
let regCodeAllRegions = [];
regCodeAllRegions = $('.settings-container').find('input:checkbox.changed').attr('data-region-code');
alert(JSON.stringify(regionCode));
Method attr only works for a single element, so it returns only the last one. You need to iterate through the list. This is an example:
let regionCodes = [];
$('input:checkbox.changed').each((i, el) => regionCodes.push($(el).data('region-code')));
console.log(regionCodes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="changed" data-region-code="1">
<input type="checkbox" class="changed" data-region-code="2">
<input type="checkbox" class="changed" data-region-code="3">
<input type="checkbox" class="changed" data-region-code="4">
<input type="checkbox" class="changed" data-region-code="5">
Another way:
let regionCodes = $('input:checkbox.changed').toArray().map((el) => $(el).data('region-code'));
console.log(regionCodes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="changed" data-region-code="1">
<input type="checkbox" class="changed" data-region-code="2">
<input type="checkbox" class="changed" data-region-code="3">
<input type="checkbox" class="changed" data-region-code="4">
<input type="checkbox" class="changed" data-region-code="5">

jQuery set value of each previous sibling of each ticked checkbox upon submit

I have been searching solutions for this and found that the most effective way is through a hacky workaround like this, but none of them has posted a working way to catching every tick and untick box for a dynamic input row using a lot of checkbox arrays.
I looked around and saw a script way -- let hidden inputs be the POST source and change value according to their adjacent checkbox upon submit. However the jquery doesn't seem to work -- it always submits a value of 0 (whatever the value attribute inside hidden inputs.
$(document).ready(function() {
$('#frm').submit(function() {
$('input[type="checkbox"]:checked').prev('.checkboxHandler').val(1);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="hidden" class="checkboxHandler" name="isHeadOfFamily[]" value="0">
<td><input type="checkbox"></td>
<input type="hidden" class="checkboxHandler" name="isEmployed[]" value="0">
<td><input type="checkbox"></td>
<! and so on-->
Your code works
I will delete this answer once we have discussed it
I have changed hidden to text and added preventDefault to show it works
$(document).ready(function() {
$('#frm').on("submit",function(e) {
e.preventDefault(); //while testing
$('input[type="checkbox"]:checked').prev('.checkboxHandler').val(1);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="frm">
<input type="text" class="checkboxHandler" name="isHeadOfFamily[]" value="0">
<td><input type="checkbox"></td>
<input type="text" class="checkboxHandler" name="isEmployed[]" value="0">
<td><input type="checkbox"></td>
<! and so on-->
<input type="submit"/>
</form>
Consider the following example.
$(function() {
function getTableData(table) {
var results = [];
$("tbody > tr", table).each(function(i, row) {
results.push({
id: $(row).data("uid"),
isHeadofHousehold: $("input", row).eq(0).prop("checked"),
isEmployed: $("input", row).eq(1).prop("checked")
});
});
return results;
}
$('#frm').on("submit", function(e) {
e.preventDefault();
var formData = getTableData($("#myTable"));
console.log(formData);
});
});
.checkbox {
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="frm">
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Head of Household</th>
<th>Employed</th>
</tr>
</thead>
<tbody>
<tr data-uid="1001">
<td>Homer Simpson</td>
<td class="checkbox"><input type="checkbox" name="isHeadOfFamily[]" checked></td>
<td class="checkbox"><input type="checkbox" name="isEmployed[]" checked></td>
</tr>
<tr data-uid="1002">
<td>Marge Simpson</td>
<td class="checkbox"><input type="checkbox" name="isHeadOfFamily[]"></td>
<td class="checkbox"><input type="checkbox" name="isEmployed[]"></td>
</tr>
</tbody>
</table>
<input type="submit" value="Save" />
</form>
You now have:
[
{
"id": 1001,
"isHeadofHousehold": true,
"isEmployed": true
},
{
"id": 1002,
"isHeadofHousehold": false,
"isEmployed": false
}
]
You can then use AJAX to POST this data back to PHP so the changes can be saved to SQL. As mentioned, you can switch them to 1 and 0 respectively if you choose.
Update
Returning to OP's desired method, consider the following.
$(function() {
$("#frm").on("change", "input[type='checkbox']", function(event) {
$(this).prev(".checkboxHandler").val($(this).prop("checked") ? 1 : 0);
});
});
.checkbox {
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="frm">
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Head of Household</th>
<th>Employed</th>
</tr>
</thead>
<tbody>
<tr data-uid="1001">
<td>Homer Simpson</td>
<td class="checkbox">
<input type="hidden" class="checkboxHandler" name="isHeadOfFamily[]" value="1" />
<input type="checkbox" checked />
</td>
<td class="checkbox">
<input type="hidden" class="checkboxHandler" name="isEmployed[]" value="1" />
<input type="checkbox" checked />
</td>
</tr>
<tr data-uid="1002">
<td>Marge Simpson</td>
<td class="checkbox">
<input type="hidden" class="checkboxHandler" name="isHeadOfFamily[]" value="0" />
<input type="checkbox" />
</td>
<td class="checkbox">
<input type="hidden" class="checkboxHandler" name="isEmployed[]" value="0" />
<input type="checkbox" />
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Save" />
</form>
This updates the hidden text box value when a User makes a change.
If you are insistent on using the original code, use the following:
$('input[type="checkbox"]:checked').prevAll('.checkboxHandler').val(1);
I strongly advise not using this, as it's a one way logic and if the User unchecks a box before the form is submitted, the change will not be captured.
Update 2
Based on the Top rated answer here, you could also do this:
<td>
<input type="hidden" name="isHeadOfFamily[]" value="0">
<input type="checkbox" name="isHeadOfFamily[]" value="1">
</td>
<td>
<input type="hidden" name="isEmployed[]" value="0">
<input type="checkbox" name="isEmployed[]" value="1">
</td>
The only caveat is that if the User checks a box, both values would get sent. So as suggested, disable the hidden upon submit if unchecked.
$("#frm").submit(function(){
$('input[type="checkbox"]:checked').prevAll().prop("disabled", true);
});

How can I write to json format with the table checkbox I selected by row to column?

I am a beginner at studying frontend. I encounter some questions that I want to write JSON format with the table checkbox I selected by row to column.
It's mean here is the db column name and its column's value. Then, I want to output like (If only Column_name's td 0,2 were checked):
{
"Column_name":["0","2"],
"Column_name_2":[]
}
<table id="tab">
<tr id ='tr1'>
<td>Column_name</td>
<td><input type="checkbox" value="0" />0</td>
<td><input type="checkbox" value="1" />1</td>
<td><input type="checkbox" value="2" />2</td>
</tr>
<tr id ='tr2'>
<td>Column_name_2</td>
<td><input type="checkbox" value="3" />3</td>
<td><input type="checkbox" value="4" />4</td>
<td><input type="checkbox" value="5" />5</td>
</tr>
</table>
<br />
<button class="btn-disp">Display Selected IDs</button>
I have some search to get each element but it seems not to meet.
document.querySelector('.btn-disp').addEventListener('click', e => {
const ids = [...document.getElementById('tr1')
.querySelectorAll('td input[type="checkbox"]:checked')]
.map(cb => cb.value);
console.log(`TD1: ${ids.join(', ')}`);
const id2 = [...document.getElementById('tr2')
.querySelectorAll('td input[type="checkbox"]:checked')]
.map(cb => cb.value);
console.log(`TD2: ${id2.join(', ')}`);
});
try the below snippet.
$('.btn-disp').click(function(){
var Column_name = {};
var Column_name_tmp = [];
var Column_name_tmp = $("input[name='Column_name']:checked").map(function(){
return $(this).val();
}).get();
Column_name['Column_name'] = Column_name_tmp;
var Column_name_2 = {};
var Column_name_2tmp = [];
var Column_name_2tmp = $("input[name='Column_name_2']:checked").map(function(){
return $(this).val();
}).get();
Column_name_2['Column_name_2'] = Column_name_2tmp;
console.log(Column_name);
console.log(Column_name_2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tab">
<tr id ='tr1'>
<td>Column_name</td>
<td><input type="checkbox" name="Column_name" value="0" />0</td>
<td><input type="checkbox" name="Column_name" value="1" />1</td>
<td><input type="checkbox" name="Column_name" value="2" />2</td>
</tr>
<tr id ='tr2'>
<td>Column_name_2</td>
<td><input type="checkbox" name="Column_name_2" value="3" />3</td>
<td><input type="checkbox" name="Column_name_2" value="4" />4</td>
<td><input type="checkbox" name="Column_name_2" value="5" />5</td>
</tr>
</table>
<br />
<button class="btn-disp">Display Selected IDs</button>

how to make checkbox unchecked when other checkbox is checked in angular

I have a table where it shows the list of deleted items.
User can either recover the item or delete permanently. i need help in making only one checkbox is checked in a table row and uncheck other checkbox when user try to check both. Also when checkbox is checked in table header, it should select all the checkboxes in that td.
$(function() {
$('input.example').on('change', function() {
$("tr").closest('input.example').not(this).prop('checked', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app>
<table>
<th>
<label>
<input type="checkbox" class="example" />Recover</label>
<label>
<input type="checkbox" class="example" />Delete</label>
</th>
<tr>
<td>
<input type="checkbox" class="example" />
</td>
<td>
<input type="checkbox" class="example" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="example" />
</td>
<td>
<input type="checkbox" class="example" />
</td>
</tr>
</table>
</div>
This is exactly the scenario where you should be using radio inputs, not checkboxes, as you get this behaviour by default without the need for any JS code. All you have to do is group the required input elements by their name attribute. Try this:
<div ng-app>
<table>
<th>
<label><input type="radio" name="foo1" />Recover</label>
</th>
<th>
<label><input type="radio" name="foo1" />Delete</label>
</th>
<tr>
<td>
<input type="radio" name="foo2" />
</td>
<td>
<input type="radio" name="foo2" />
</td>
</tr>
<tr>
<td>
<input type="radio" name="foo3" />
</td>
<td>
<input type="radio" name="foo3" />
</td>
</tr>
</table>
</div>
i figured it out myself without using radio buttons and its working fine.
JS code
$scope.uncheckPermDelete = function (ip) {
if($("input[name=perm_delete_check_"+ ip.id +"]").prop('checked', true)) {
$("input[name=perm_delete_check_"+ ip.id +"]").prop('checked', false);
ip.perm_delete = 0;
}
};
$scope.uncheckRecover= function (ip) {
if($("input[name=recover_check_"+ ip.id +"]").prop('checked', true)) {
$("input[name=recover_check_"+ ip.id +"]").prop('checked', false);
ip.deleted = 1;
}
};
HTML code
<td ><input class="recover_check" name="recover_check_{{ip.id}}" ng-change="uncheckPermDelete(ip)" type="checkbox" ng-model="ip.deleted" ng-true-value="0" ng-false-value="1" /></td>

Categories

Resources