Button not being enabled after click on checkboxes - javascript

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

Related

Use JavaScript to get value of the for each

I'm new using JavaScript. I need to get the value ${prdcts.precioUnidad} of the checked line. The idea is to set the total price in a dynamic way, so when the user checks or unchecks each line the value of total either adds the new value when checked, or subtracts the previous value when unchecked.
I tried to get the value using the getElement() methods, but I don't know how to access the value of the variable within that specific row.
This is the HTML:
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ventas</title>
</head>
<body>
<center><h1>Venta de Productos</h1>
<form action="venta.htm" method="post">
<table id="tableID" border="4">
<tbody><tr>
<th>ID</th>
<th>Nombre</th>
<th>Valor</th>
<th>Comprado</th>
</tr>
<tr>
<td>2</td>
<td>Chupetin</td>
<td>5.0</td>
<td><input name="check" type="checkbox" value="2" label="2" path="prdcts"></td>
</tr>
<tr>
<td>3</td>
<td>Alfajor DDL</td>
<td>30.0</td>
<td><input name="check" type="checkbox" value="3" label="3" path="prdcts"></td>
</tr>
<tr>
<td>4</td>
<td>Sanguche Mila</td>
<td>60.0</td>
<td><input name="check" type="checkbox" value="4" label="4" path="prdcts"></td>
</tr>
</tbody></table>
<br>
<br>
<br>
<table border="4">
<tbody><tr>
<td>Total Compra: <input name="total" id="total" type="number" readonly="" value="0"></td>
</tr>
<tr>
<td>Monto Pagado: <input name="monto" id="monto" type="number" value="0"></td>
</tr>
<tr>
<td>Vuelto: <input name="vuelto" id="vuelto" type="number" readonly="" value="0"></td>
</tr>
<tr>
<td><input name="begin" onclick="calcularVuelto()" type="button" value="Calcular Vuelto"></td>
</tr>
</tbody></table>
<br>
<br>
<input name="clear" onclick="window.location.href = 'venta.htm'" type="button" value="Borrar venta">
<input name="begin" onclick="window.location.href = 'principal.htm'" type="button" value="Inicio">
<input name="confirm" type="submit" value="Confirmar Venta">
<br>
</form>
</center>
<script>
// Make it an Array with "Array.from" so we can use reduce() on it
var $$checkboxes = Array.from(document.querySelectorAll('input[name=check]')),
$total = document.getElementById('total');
// For each checkbox
$$checkboxes.forEach(function ($checkbox) {
// When its value changes, update total
$checkbox.addEventListener('change', updateTotal);
});
function updateTotal() {
// For each checkbox
alert("aca");
var total = $$checkboxes.reduce(function (sum, $checkbox) {
// If it's checked
alert("aca2")
if ($checkbox.checked) {
var price = $checkbox.parentNode.parentNode // parent <tr>
.querySelectorAll('td')[2].innerText.trim(); // remove spaces
// Add price to the sum
return sum + parseFloat(price);
} else {
// If it's not checked, just return the current sum
return sum;
}
}, 0);
$total.value = total.toFixed(2); // Always 2 decimals
}
function calcularVuelto() {
var total = document.getElementById("total").value;
var pago = document.getElementById("monto").value;
var fTotal = parseFloat(total);
var fPago = parseFloat(pago);
totalResta = fPago - fTotal;
document.getElementById("vuelto").value = totalResta;
}
</script>
</body></html>
You can use Array.prototype.reduce() to calculate the total:
// Make it an Array with "[].slice.call" so we can use reduce() on it
var $$checkboxes = [].slice.call(document.querySelectorAll('input[name=check]')),
$total = document.getElementById('total');
// For each checkbox
$$checkboxes.forEach(function ($checkbox) {
// When its value changes, update total
$checkbox.addEventListener('change', updateTotal);
});
function updateTotal() {
// For each checkbox
var total = $$checkboxes.reduce(function (sum, $checkbox) {
// If it's checked
if ($checkbox.checked) {
var price = $checkbox.parentNode.parentNode // parent <tr>
.querySelectorAll('td')[2].innerText.trim(); // remove spaces
// Add price to the sum
return sum + parseFloat(price);
} else {
// If it's not checked, just return the current sum
return sum;
}
}, 0);
$total.value = total.toFixed(2); // Always 2 decimals
}
<table border="4">
<tr><th>ID</th> <th>Nombre</th> <th>Valor</th> <th>Comprado</th> </tr>
<tr><td>x</td><td>X</td><td>5.99</td><td><input name="check" type="checkbox" value="x" label="X"/></td></tr>
<tr><td>y</td><td>Y</td><td>3.95</td><td><input name="check" type="checkbox" value="y" label="Y"/></td></tr>
<tr><td>z</td><td>Z</td><td>14.20</td><td><input name="check" type="checkbox" value="z" label="Z"/></td></tr>
</table>
<p>Total Compra: <input name="total" id="total" type="number" value="0" readonly/></p>
The checked flag is either on or off. It doesn't take an argument. So it looks like
<input type="checkbox" name="name" checked> checked </input>
<br/>
<input type="checkbox" name="name"> unchecked</input>
In your code you'll need something like: ${prdcts.idProducto ? "checked" : ""}

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>

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/

Get sum of radio button value using javascript function in table

I am looking to get the sum of these 4 different values without query through a the radio buttons.
Here my javascript and html, once I click on submit, 0 appears in the total field, thank you for your help!
<!DOCTYPE html>
<html>
<body>
<script>
function checkRadio() {
var selectedAge="";
var selectedBmi="";
var selectedDiabete="";
var description="";
var len = document.row.length;
var i;
function init(){
for (i = 0; i<len; i++) {
if (document.row[i].value);
break;
}
if (selectedAge == "") {
document.getElementByid("radio_error").innnerHTML = "no option selected";
return false
}
else {
document.getElementById("radio_error").innerHTML = "";
return true;
}
}
init();
}
</script>
<script>
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
var val3 = parseInt(document.getElementById("value3").value);
var val4 = parseInt(document.getElementById("value4").value);
var ansD = document.getElementById("answer");
ansD.value = val1 + val2 + val3 + val4;
}
</script>
<table>
<tr>
<th scope="col"></th>
<th scope="col">noRisk</th>
<th scope="col">lowRisk</th>
<th scope="col">mediumRisk</th>
<th scope="col">HighRisk</th>
</tr>
<tr>
<th scope="row"><div class="lefttext">How old are you?</div></th>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="0"checked>1-25</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="5">26-40</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="8">41-60</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="10">1-25</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">What is you BMI?</div></th>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="0" checked>0-25</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="0">26-30</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="9">31-35</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="10">35+</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">Does anybody in your family have diabetes?</div></th>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="0" checked>No</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="7">Grandparent</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="15">Sibling</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="15">Parent</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">How would you describe your diabete</div></th>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="0" checked >Low sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="0">Normal sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="7">Quite high sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="10">High sugar</td>
</tr>
</table>
<input type="button" name="Sumbit" value="Submit" onclick="javascript:addNumbers()"/>
Total = <input type="text" id="answer" name="answer" value=""/>
</body>
You have to specify that you only want the value of the checked checkboxes. You now select all the checkboxes. Try this instead:
function addNumbers()
{
var val1 = parseInt(document.querySelector('input[name = "selectedAge"]:checked').value);
var val2 = parseInt(document.querySelector('input[name = "selectedBmi"]:checked').value);
var val3 = parseInt(document.querySelector('input[name = "selectedDiabete"]:checked').value);
var val4 = parseInt(document.querySelector('input[name = "description"]:checked').value);
var ansD = document.getElementById("answer");
ansD.value = val1 + val2 + val3 + val4;
}
Here is working example.
Basically:
var sum = function(a, b) {
return a + b;
};
var getPollResult = function() {
var checkedRadioButtons = document.querySelectorAll('table input[type="radio"]:checked');
return Array.prototype.map.call(checkedRadioButtons, function(radio) { return parseInt(radio.value, 10); }).reduce(sum, 0);
};
document.getElementById("submit").addEventListener('click', function() {
document.getElementById("answer").value = getPollResult();
});

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

Categories

Resources