Javascript "check all" a subset of multiple checkbox groups - javascript

My checkbox group are in html table. Each row has checbox group. I am trying to put a select_all button in each row of table (which can select all or unselect all the checkbox of that particular row). I used javascript for the purpose. However, select all button checks all the checkbxes of the table. I couldnt find a way to select_all button applicable to only single row. Any idea?
I think the change in javascript can solve this prob, but I am unfamiliar with javascript orjquery.
function checkAll(bx) {
var cbs = document.getElementsByTagName('input');
for (var i = 0; i < cbs.length; i++) {
if (cbs[i].type == 'checkbox') {
cbs[i].checked = bx.checked;
}
}
}
<form action="backend.php" method="POST" target="iframe_3">
<table border="10" width="900" bordercolor="green">
<tr>
<td colspan="3" style="background-color:#7F77AE">DNA</td>
<td><input type="checkbox" name="check_list[]" value="value 1">seq</td>
<td><input type="checkbox" name="check_list[]" value="value 2">codon</td>
<td><input type="checkbox" onclick="checkAll(this)">Select_all</td>
</tr>
<tr>
<td colspan="3" style="background-color:#7F77AE">RNA</td>
<td><input type="checkbox" name="check_list2[]" value="value 3">seq</td>
<td><input type="checkbox" name="check_list2[]" value="value 4">codon</td>
<td><input type="checkbox" onclick="checkAll(this)">Select_all</td>
</tr>
</table>

Using jQuery, this is a kind of trivial task. You actually just need to query for the <input> nodes within you specific <tr> node.
function checkAll(bx) {
var cbs = $( bx ).closest( 'tr' ).find( 'input:checkbox' );
for(var i=0; i < cbs.length; i++) {
if(cbs[i].type == 'checkbox') {
cbs[i].checked = bx.checked;
}
}
}
Without jQuery, this would look like
function checkAll(bx) {
var cbs = bx.parentNode.parentNode.querySelectorAll( 'input[type="checkbox"]' );
for(var i=0; i < cbs.length; i++) {
if(cbs[i].type == 'checkbox') {
cbs[i].checked = bx.checked;
}
}
}

jQuery way:
$(this).closest('tr').find('input[type=checkbox]').prop('checked', true);
fiddle

check this
<tr>
<td colspan="3" style="background-color:#7F77AE">DNA</td>
<td><input type="checkbox" name="check_list[]" value="value 1">seq</td>
<td><input type="checkbox" name="check_list[]" value="value 2">codon</td>
<td><input type="checkbox" onclick="checkAll(this)" id="check_list" role="selectall">Select_all</td>
</tr>
<tr>
<td colspan="3" style="background-color:#7F77AE">RNA</td>
<td><input type="checkbox" name="check_list2[]" value="value 3">seq</td>
<td><input type="checkbox" name="check_list2[]" value="value 4">codon</td>
<td><input type="checkbox" onclick="checkAll(this)" id="check_list2" role="selectall">Select_all</td>
</tr>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(e) {
$('[role="selectall"]').each(function(){
// + handle click of select all
$(this).bind('click.selall', handleSelectAll);
var group_name = $(this) .attr('id')+'[]';
$('[name='+group_name+']').bind('click.single', handleSingle);
})
});
function handleSingle(){
var grp_name = $(this).attr('name');
var sel_all_id = grp_name.replace('[','').replace(']', '');
if( $('[name='+grp_name+']').length == $('[name='+grp_name+']:checked').length){
$('#'+grp_name).prop('checked', true);
}else{
$('#'+grp_name).prop('checked', false)
}
}
function handleSelectAll(){
var group_name = $(this) .attr('id')+'[]';
if( $(this).is(':checked')){
$('[name='+group_name+']').prop('checked', true);
}else{
$('[name='+group_name+']').prop('checked', false);
}
}
})(jQuery)
</script>
the key is the id of the select all check box is same as the group name without paranthesis

Related

how to connect table with his checkboxes?

i want to check all checkbox in first table if i press on first checkbox and i want to check all checkbox in second table if i press on second checkbox , but when i press on first or second checkbox it checkbox all in two table
function checkAll(t,ele) {
var table= document.getElementById(t);
var checkboxes = ("table td input[type=checkbox]");
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
console.log(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 get all checkboxes within a table by class name
document.getElementById("tableId").getElementsByClassName("checkboxclass");
Full snippet below:
document.getElementById('toggleOnFirst').onclick = function(){
checkAll('firstTable', true)
}
document.getElementById('toggleOffFirst').onclick = function(){
checkAll('firstTable', false)
}
document.getElementById('toggleOnSecond').onclick = function(){
checkAll('secondTable', true)
}
document.getElementById('toggleOffSecond').onclick = function(){
checkAll('secondTable', false)
}
function checkAll(table, status) {
// Get all checkboxes by class within a table
var checkboxes = document.getElementById(table).getElementsByClassName("check");
// Loop all checkboxes and check / uncheck them
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i]
checkbox.checked = status;
}
}
<table id="firstTable" style="width:100%" >
<tr>
<td> <input type="checkbox" class="check" name="check" value="0"></td>
</tr>
<tr>
<td> <input type="checkbox" class="check" name="check" value="0"></td>
</tr>
<tr>
<td> <input type="checkbox" class="check" name="check" value="0"></td>
</tr>
</table>
<button id="toggleOnFirst">
Toggle on
</button>
<button id="toggleOffFirst">
Toggle off
</button>
<table id="secondTable" style="width:100%" >
<tr>
<td> <input type="checkbox" class="check" name="check" value="0"></td>
</tr>
<tr>
<td> <input type="checkbox" class="check" name="check" value="0"></td>
</tr>
<tr>
<td> <input type="checkbox" class="check" name="check" value="0"></td>
</tr>
</table>
<button id="toggleOnSecond">
Toggle on
</button>
<button id="toggleOffSecond">
Toggle off
</button>

Select multiple check boxes by clicking the first one

I have an html table with many check boxes. If I select the first check box, the next one is automatically selected. Does someone know how to do this? Also, the exact row number in table is unknown.
function toggle(source) {
var row_index = $("#checkFirst").index();
var row_first = $(".row").index();
checkboxes = document.getElementsByName('row');
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (i == row_index && i == row_first) {
checkboxes[i].checked = source.checked;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody data-bind="foreach: list">
<tr>
<td><input type="checkbox" id="checkFirst" onClick="toggle(this)" /></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
</tr>
</tbody>
You can use below code for this. First give class checkbox to all other checkboxes. Hope this can help you
$(function(){
$("#checkFirst").click(function () {
$('.checkbox').attr('checked', this.checked);
});
$(".checkbox").click(function(){
if($(".checkbox").length == $(".checkbox:checked").length) {
$("#checkFirst").attr("checked", "checked");
} else {
$("#checkFirst").removeAttr("checked");
}
});
});
You can try with below code. It will help you.
jQuery file:
https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
<table>
<tbody data-bind="foreach: list">
<tr id="first">
<td><input type="checkbox" id="checkfirst" onClick="toggle('first',this.id)"/></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox" name="row"></td>
</tr>
<tr id="second">
<td><input type="checkbox" id="checksecond" onClick="toggle('second',this.id)"/></td>
<td><input type="checkbox" ></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
</tr>
</table>
Script
<script>
function toggle(source,id) {
chcked = $('#'+id).prop( "checked" );
if(chcked)
{
$('#'+source+' :checkbox').each(function() {
this.checked = true;
});
}
else
{
$('#'+source+' :checkbox').each(function() {
this.checked = false;
});
}
}
</script>
You can try this snippet.
function handleCheck(e) {
let will_change = false;
if (e.shiftKey && this.checked) {
checkboxes.forEach(element => {
if (element === this || element === last_checked) {
will_change = !will_change;
}
if (will_change) {
element.checked = true;
}
});
}
last_checked = this;
}
Then add a click event listener to each of the checkboxes you want to act as a group
https://codepen.io/anon/pen/GyQEJZ
this makes the first checkbox a global control for all
$('#checkFirst').on('change',function(){
if($(this).is(':checked'))
$('input[type="checkbox"]').prop('checked', true);
else
$('input[type="checkbox"]').prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<tbody data-bind="foreach: list">
<tr>
<td><input type="checkbox" id="checkFirst"/></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
</tr>
</tbody>
and this is to select the following checkboxes in the same row
$('input[type="checkbox"]').on('change',function(){
$(this).parent().nextAll().find('input[type="checkbox"]').prop('checked', $(this).is(':checked'));
});

How to remeber clicked buttons after page refresh with javascript?

Following code used to highlight table record when the checkbox is clicked. But once I refresh the page highlighted records disappear.How can I remain same highlighted record even after page refresh?
<style>
.highlight {
background-color: yellow;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#Table input").click(function() {
if ($(this).is(":checked")) {
$(this).parent().parent().addClass("highlight");
} else {
$(this).parent().parent().removeClass("highlight");
}
});
});
</script>
<body>
<div class="col-lg-10">
<form name="f">
<table id="Table" border="1"><tr>
<td><input type="checkbox" name="cb1" id="cb1" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" /></td>
<td>Click me</td>
</tr></table>
</div>
You will have to save the state somewhere, either in the url as a query string or you could use the browser localStorage. Then when the page loads, check that state and highlight accordingly.
Try something like this:
$("#Table input").click(function() {
if ($(this).is(":checked")) {
if(!localStorage.checked) {
localStorage.checked = [];
}
localStorage.checked.push($(this));
$(this).parent().parent().addClass("highlight");
} else {
for (var i = 0;i < localStorage.checked.length; i++) {
var itemAtIndex = localStorage.checked[i];
if(itemAtIndex == $(this)){
localStorage.splice(i, 1);
}
}
$(this).parent().parent().removeClass("highlight");
}
});
//on page load
for (var i = 0;i < localStorage.checked.length; i++) {
var itemAtIndex = localStorage.checked[i];
itemAtIndex.parent().parent().addClass("highlight");
}
The idea written in the answer of stackoverfloweth was correct however his code indeed did not work.
Heres your example using localStorage that does work (wont work in preview window here but will if you try it locally):
<style>
.highlight {
background-color: yellow;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
var checked = [];
$(document).ready(function() {
if (localStorage.getItem("checked") == null)
localStorage.setItem("checked", checked);
$("#Table input").click(function() {
if ($(this).is(":checked")) {
$(this).parent().parent().addClass("highlight");
checked.push($(this).attr("id"));
} else {
$(this).parent().parent().removeClass("highlight");
checked.remove($(this).attr("id"));
}
localStorage.setItem("checked", JSON.stringify(checked));
});
var saved = JSON.parse(localStorage.getItem("checked"));
for (var i = 0;i < saved.length; i++) {
var itemAtIndex = $("#" + saved[i] + "");
itemAtIndex.click();
itemAtIndex.parent().parent().addClass("highlight");
}
});
</script>
<body>
<div class="col-lg-10">
<form name="f">
<table id="Table" border="1"><tr>
<td><input type="checkbox" name="cb1" id="cb1" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" /></td>
<td>Click me</td>
</tr></table>
</div>

jquery - get html string of table cells

I have some HTML that is being generated by some server-side code. The HTML that's generated looks like this:
<table id="myChoices">
<tr>
<td><input type="radio" name="choice" value="1" /></td>
<td>Monday</td>
<td>Mar 7</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="2" /></td>
<td>Tuesday</td>
<td>Mar 8</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="3" /></td>
<td>Wednesday</td>
<td>Mar 9</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="4" /></td>
<td>Thursday</td>
<td>Mar 10</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="5" /></td>
<td>Friday</td>
<td>Mar 11</td>
</tr>
</table>
When a user makes a choice, I need to get the two cells next to it. For example, if someone chooses the third option, I'm trying to get the following:
<td>Wednesday</td><td>Mar 9</td>
In my attempt to do this, I have the following jQuery:
function getHtml() {
var html = '';
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.parent().parent();
var cells = grandparent.children();
var html = '';
for (var i = 0; i < cells.length; i++) {
if (i > 0) {
var cellHtml = cells[i];
html += cellHtml;
}
}
}
return html;
}
Unfortunately, my approach is not working. When I do the following:
var test = getHtml();
console.log(test);
I see the following in the console window:
[object HTMLTableCellElement][object HTMLTableCellElement]
Why? How do I get the actual HTML string?
Use outerHTML, instead you are storing the jQuery object in the variable.
var cellHtml = cells[i];
should be
var cellHtml = cells[i].outerHTML;
JS
function getHtml() {
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.closest('tr'),
cells = grandparent.children();
var html = '';
for (var i = 1; i < cells.length; i++) {
html += cells[i].outerHTML + ' ';
}
}
return html;
}
js Fiddle
I propose you change the script a bit to simplify the process altogether.
$("#myChoices input").change( function() {
var string = $(this).parent().nextAll("td").text();
});
Variable "string" will contain the text you are looking for.
I believe you could just use something simple like:
$("input[type='radio']:checked").parents("tr").first().text();
Example: http://codepen.io/cchambers/pen/ONNawo
JSFIDDLE DEMO
Use this instead
var cellHtml = cells[i].outerHTML;
Complete JS
var html = '';
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.parent().parent();
var cells = grandparent.children();
var html = '';
for (var i = 0; i < cells.length; i++) {
if (i > 0) {
var cellHtml = cells[i].outerHTML; //change here
html += cellHtml;
}
}
}
console.log(html);
Result format:
<td>Monday</td><td>Mar 7</td>
The easiest way would be to use the .html() method on a dynamic tr which contains the other two td elements.
A trick is to clone them then wrap them in a tr and get the html of that
var others = $(this).closest('td').siblings().clone();
alert( others.wrapAll('<tr>').parent().html());
$(function(){
$('#myChoices [name="choice"]').on('change', function(){
var others = $(this).closest('td').siblings().clone();
alert( others.wrapAll('<tr>').parent().html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myChoices">
<tr>
<td><input type="radio" name="choice" value="1" /></td>
<td>Monday</td>
<td>Mar 7</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="2" /></td>
<td>Tuesday</td>
<td>Mar 8</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="3" /></td>
<td>Wednesday</td>
<td>Mar 9</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="4" /></td>
<td>Thursday</td>
<td>Mar 10</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="5" /></td>
<td>Friday</td>
<td>Mar 11</td>
</tr>
</table>
In a function form it would be
function getHtml() {
var item = $("#myChoices input[type='radio']:checked");
var otherTD = item.closest('td').siblings().clone();
return otherTD.wrapAll('<tr>').parent().html();
}
You could use jquery's siblings method:
var textContents = $("#myChoices input[type='radio']:checked").siblings().html();

Select all checkboxes JS toggle issue

Hoping someone can help me overcome my Javascript ignorance.
I've got a form that includes checkboxes and I've got a piece of JS that toggles selecting/deselecting all the boxes. And so far, it all works as expected.
The wrench in the works is that I've got multiple groups of checkboxes in this form and I would like to select/deselect by group, not all the checkboxes in the form. This is a sample of the php and html. As you can see, the form is in a table and there is a checkbox in the header row that performs the action. 'resources_req' is the name of the checkbox element in the form
<form method="post" name="add_reservation">
<?php for($x=0; $x<count($groups); $x++) : // make seperate display for each group ?>
<div class="group_<?php echo $group_label; ?>">
<table class="res">
<tr>
<!-- form: checkbox all -->
<?php if($make_res == 'enter') : // adds checkbox to check all ?>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<?php endif; ?>
<!-- end form: checkbox all -->
</tr>
...
foreach($resources as $resource) { // for each resource/laptop
$form_start = '<td>';
$form_start .= '<input type="checkbox" name="resources_req[]" value="'.$resource['id'].'"';
$form_start .= ' />';
$form_start .= '</td>';
}
...
</table>
</div>
<?php endfor; // loop for each group ?>
<input type="submit" name="add_reservation" value="Make this reservation" />
</form>
Here is the JS being called:
function toggle(source, element) {
checkboxes = document.getElementsByName(element);
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
Best I can put together, the 'this' in the script call is referring to the form. I thought if maybe I put each of these groups in to their own div class, I could then somehow refer to just that but now I'm just lost. Any help or suggestions appreciated!
EDIT: I asked for suggestions and it's been suggested I post only the html:
<form method="post" name="add_reservation">
<div class="group_A">
<table>
<tr>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<th>Name</th>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="1" /></td>
<td>John</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="2" /></td>
<td>Bill</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="3" /></td>
<td>Fred</td>
</tr>
</table>
</div>
<div class="group_b">
<table>
<tr>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<th>Name</th>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="4" /></td>
<td>George</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="5" /></td>
<td>Tom</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="6" /></td>
<td>Raymons</td>
</tr>
</table>
</div>
<input type="submit" name="add_reservation" value="Make this reservation" />
</form>
I changed a few things:
First, instead of passing the value of name, I'm passing the tagName of 'input' instead.
<input type="checkbox" onClick="toggle(this, 'input')" />
Then in the toggle() function, I select the parentNode of the source element, and do a getElementsByTagName() so that I only get the input elements in the local div.
Also, I changed the for-in loop to a standard for loop, which is the proper type of loop to iterate over indexed elements. The for-in can actually give some problems.
function toggle(source, element) {
var checkboxes = source.parentNode.getElementsByTagName(element);
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
Live Example: http://jsfiddle.net/37mT2/
Alternatives:
Instead of parentNode, select the ancestor <div> element by assigning it an ID, and passing it to your toggle() function.
<input type="checkbox" onClick="toggle(this, 'input', 'someUniqueId_1')" />
<input type="checkbox" onClick="toggle(this, 'input', 'someUniqueId_2')" />
function toggle(source, element, id) {
var checkboxes = document.getElementById( id ).getElementsByTagName('input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
Or you could traverse up the parent nodes until you reach your first <div> element:
<input type="checkbox" onClick="toggle(this, 'input')" />
function toggle(source, element) {
while( source && source = source.parentNode && source.nodeName.toLowerCase() === 'div' ) {
; // do nothing because the logic is all in the expression above
}
var checkboxes = source.getElementsByTagName('input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
Or you could give the <div> elements at that level a common class name and traverse up the parent nodes until you reach that class. In the code below, your <div> elements class is "someClassName":
<input type="checkbox" onClick="toggle(this, 'input')" />
function toggle(source, element) {
while( source && source = source.parentNode && source.className === 'someClassName' ) {
; // do nothing because the logic is all in the expression above
}
var checkboxes = source.getElementsByTagName('input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
EDIT: Fixed a typo. I had getElementsById instead of getElementById.
Best I can put together, the 'this' in the script call is referring to the form. I thought if maybe I put each of these groups in to their own div class, I could then somehow refer to just that but now I'm just lost. Any help or suggestions appreciated!
http://jsfiddle.net/JG4uf/
JavaScript Loops: for...in vs for

Categories

Resources