how to connect table with his checkboxes? - javascript

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>

Related

Button not being enabled after click on checkboxes

So, I have created a table with checkboxes and I want the user to check at least two options in order to enable the button to submit the answers.
HTML
<body>
<h1>Checked two options</h1>
<br />
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" onclick="EnableButton()" />
</body>
And I have this function, but it's not working. I'm using a looping to count how many options have been checked by the user, but it doesn't work.
JS
function EnableButton() {
var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.getElementsByTagName("INPUT");
var counter = 0;
for (let i = 0; i < marcados.length; i++) {
if (checkeds[i].checked) {
counter++;
}
}
if (counter >= 2) {
document.getElementById("mybtn").disabled = false;
} else {
document.getElementById("mybtn").disabled = true;
}
}
What am I doing wrong?
You need to check for whether the button needs to be enabled when the inputs get checked, not when the button gets clicked.
The nicest, most concise way to do this is:
const table = document.querySelector('#tblFoods');
table.addEventListener('change', () => {
const checkedCount = [...table.querySelectorAll('input')].reduce((a, input) => a + input.checked, 0);
document.getElementById("mybtn").disabled = checkedCount < 2;
});
<h1>Checked two options</h1>
<br/>
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" />
Your original code, tweaked, works too, but is pretty verbose in comparison.
document.querySelector('#tblFoods').addEventListener('change', () => {
var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.getElementsByTagName("INPUT");
var counter = 0;
for(let i =0; i < checkeds.length;i++)
{
if(checkeds[i].checked)
{
counter++;
}
}
if(counter>=2)
{
document.getElementById("mybtn").disabled = false;
}
else
{
document.getElementById("mybtn").disabled = true;
}
});
<h1>Checked two options</h1>
<br/>
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" />
You have to handle the changes on each checkbox element separately and finally, the submit button. You can do something like the below.
Note: See how the onClick event handlers are used on each input type checkbox element and on the submit button separately. Also, we have to reset everything when submitting.
A possible solution:
let checks_counter = 0;
function EnableButton(checkbox) {
if (checkbox.checked) {
checks_counter++;
}
if (checks_counter > 2) {
document.getElementById("mybtn").disabled = false;
} else {
document.getElementById("mybtn").disabled = true;
}
}
function submitHandler() {
var elements = document.getElementsByTagName('input');
//unchecking everything
for (var i = elements.length; i--;) {
if (elements[i].type == 'checkbox') {
elements[i].checked = false;
}
}
//resetting the counter and disabling the button
checks_counter = 0;
document.getElementById("mybtn").disabled = true;
}
<body>
<h1>Checked two options</h1>
<br/>
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" onChange="EnableButton(this)" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" onChange="EnableButton(this)" /><label for="chkLasagna">Lasagna</label></td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" onChange="EnableButton(this)" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" onChange="EnableButton(this)" /><label for="chkBarbecue">Barbecue</label></td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" onclick="submitHandler()" />
</body>
You need to call your Enable function when you check boxes. Here's a working example: https://codesandbox.io/s/proud-architecture-ou5l2?file=/src/index.js
using your existing code:
var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.querySelectorAll("input");
const btn = document.getElementById("mybtn");
function enableButton() {
var counter = 0;
for (let i = 0; i < checkeds.length; i++) {
if (checkeds[i].checked) {
counter++;
}
}
if (counter >= 2) {
btn.disabled = false;
} else {
btn.disabled = true;
}
}
const handleClick = () => {
enableButton();
// do whatever else you need in here
};
checkeds.forEach((box) => box.addEventListener("click", handleClick));
You have to run your function when the user select the food, not when the user click the button. A simple solution is removing the onclick event from the button and adding the onchange event in every input:
<h1>Checked two options</h1>
<br />
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" onchange="EnableButton()" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" onchange="EnableButton()" /><label for="chkLasagna">Lasagna</label>
</td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" onchange="EnableButton()" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" onchange="EnableButton()" /><label for="chkBarbecue">Barbecue</label>
</td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" />
You could use something like:
document.querySelectorAll("input[type='checkbox']").forEach(e => e.addEventListener("click", () => {
const submitButton = document.querySelector("#mybtn");
if (!submitButton) return;
const checkedInputs = document.querySelectorAll("#tblFoods input[type='checkbox']:checked").length;
submitButton.disabled = checkedInputs < 2;
}));
In other words, every time a checkbox is clicked, a check is run on how many checkboxes are checked in total. If this amount is greater than or equal to two, the button is enabled, otherwise it is disabled.
Maybe i am wrong but since u had initialized counter = 0, every time that the function its called, it will automatically set to 0, so u should declare it globally in order to be an effective counter.
var counter = 0;
function EnableButton()
{
var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.getElementsByTagName("INPUT");
for(let i =0; i < checkeds.length;i++)
{
if(checkeds[i].checked)
{
counter++;
}
}
if(counter>=2)
{
document.getElementById("mybtn").disabled = false;
}
else
{
document.getElementById("mybtn").disabled = true;
}
}

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>

Validate whether grouped radio boxes are checked

I'm trying to check wether at least one radio button per group has been checked an would appreciate some help for my particular case very much.
<tr>
<td> Group1 </td>
<td><input type="radio" id="wahl1" name="wahl1" value="1"></td>
<td><input type="radio" id="wahl1" name="wahl1" value="2"></td>
<td><input type="radio" id="wahl1" name="wahl1" value="3"></td>
<td><input type="radio" id="wahl1" name="wahl1" value="4"></td>
<td><input type="radio" id="wahl1" name="wahl1" value="5"></td>
<td><input type="radio" id="wahl1" name="wahl1" value="6"></td>
<td><input type="radio" id="wahl1" name="wahl1" value="7"></td>
</tr>
<tr>
<td> Group2 </td>
<td><input type="radio" id="wahl2" name="wahl2" value="1"></td>
<td><input type="radio" id="wahl2" name="wahl2" value="2"></td>
<td><input type="radio" id="wahl2" name="wahl2" value="3"></td>
<td><input type="radio" id="wahl2" name="wahl2" value="4"></td>
<td><input type="radio" id="wahl2" name="wahl2" value="5"></td>
<td><input type="radio" id="wahl2" name="wahl2" value="6"></td>
<td><input type="radio" id="wahl2" name="wahl2" value="7"></td>
</tr>
<tr>
I was trying to solve this with a pure javascipt function which for my purposes has to be defined inside a button like this:
<input name="submFragebogen2" type="submit" id="fragebogen2" value="Absenden" style="display: none">
<input type="button" value="Absenden" onclick="
function test2() {
var radios = document.getElementsByName("input");
var counter = 0;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
counter = counter + 1;
}
}
if (counter != 2) {
alert('Please choose an option in each row.');
} else {
var subButton2 = document.getElementsByName('submFragebogen2')[0];
subButton2.style.display='inline';
subButton2.click();
subButton2.style.display='none'
}
};
test2();"
use querySelectorAll to get only radio button.
document.getElementsByName("input") will return all type of input.
e.g. button,textfield,hidden field.etc.
function test2() {
var radios = document.querySelectorAll("input[type=radio]")
var counter = 0;
for (var i = 0, len = radios.length; i < len; i++) {
...
}
if (counter != 2) {
alert('Please choose an option in each row.');
} else {
..
}
};
HTML :
<input type="button" value="Absenden" onclick="test2()"/>
some errors in the html code. The id should be unique. remove the same id of the inputs.
with pure javascript you need this code:
function checkRadios() {
var wahl1RadiosChecked = false;
var wahl2RadiosChecked = false;
var wahl1Radios = document.getElementsByName('wahl1');
var wahl2Radios = document.getElementsByName('wahl2');
for( i = 0; i < wahl1Radios.length; i++ ) {
if( wahl1Radios[i].checked ) {
wahl1RadiosChecked = true;
}
}
for( i = 0; i < wahl2Radios.length; i++ ) {
if( wahl2Radios[i].checked ) {
wahl2RadiosChecked = true;
}
}
if (wahl1RadiosChecked === false || wahl2RadiosChecked === false) {
alert('Please choose an option in each row.');
} else {
var subButton2 = document.getElementsByName('submFragebogen2')[0];
subButton2.style.display='inline';
subButton2.click();
subButton2.style.display='none';
}
}
Inside the button you need to call this function.
Here is the example: https://jsbin.com/wujuwimide/edit?html,js,console,output
Of course with jquery you avoid having so much code.
You can do this using JQuery with the following code:
$("[name=wahl1]:checked").length > 0
The selector will select only inputs with name "wahl1" that has been checked. Then you just see if there are more than one of them.
If you are looking for a pure JavaScript code try this:
var elements = document.getElementsByName("wahl2"), checked = false;
for(var i=0; i<elements.length-1; i++){
checked = checked || elements[i].checked;
}
if(!checked){
alert("Please select at least one.");
}
JSFiddle: https://jsfiddle.net/z6eud4kx/

Javascript "check all" a subset of multiple checkbox groups

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

How to remove value has been exist in list table tr?

I have a sample code:
<table id="modem_list">
<tr class="input_1" name="modem">
<td>iPad 1<input type="hidden" value="1" class="output_1"></td>
</tr>
<tr class="input_2" name="modem">
<td>iPad 2<input type="hidden" value="2" class="output_2"></td>
</tr>
<tr class="input_1" name="modem">
<td>iPad 1<input type="hidden" value="1" class="output_1"></td>
</tr>
</table>
<input type="button" class="submit" onclick="update()" value="submit" />
and javascript
function update() {
var table = document.getElementById("modem_list");
var rowCount = table.rows.length;
for(var i=0; i<rowCount-1; i++) {
for(var j=i+1; j<rowCount; j++) {
if(table.rows[i] == table.rows[j]) {
rowCount--;
for(var k=j; k<rowCount; k++) {
table.rows[k] = table.rows[k+1];
table.deleteRow(k);
k--;
}
}
}
}
}
How to fix result is:
<table id="modem_list">
<tr class="input_1" name="modem">
<td>iPad 1<input type="hidden" value="1" class="output_1"></td>
</tr>
<tr class="input_2" name="modem">
<td>iPad 2<input type="hidden" value="2" class="output_2"></td>
</tr>
</table>
Assuming you want to remove the repeated tr elements based on their classes, you can try this:
function update() {
//caches a reference to which table we're working with
var table = document.getElementById("modem_list");
//gets all its rows
var trs = table.rows;
//iterates through all rows
for (var i=0; i<trs.length; i++) {
//stores possible dupes in an array
var dupes = table.getElementsByClassName(trs[i].className);
//if there are any dupes.. (more than 1 element with same class)
if (dupes.length > 1)
//removes all repeated elements except the first (index 0)
for (var j=1; j<dupes.length; j++)
dupes[j].parentNode.removeChild(dupes[j]);
}
}
JSFiddle

Categories

Resources