Validate whether grouped radio boxes are checked - javascript

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/

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

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();

Cannot Loop Through Rows of a Table in Javascript or Jquery

There are lots of examples on the internet, including SO, telling people how to loop through the rows of a table and get the values using Javascript or Jquery. Unfortunately, none of these examples work for me:
JavaScript:
var table = document.getElementById("tbInvoiceDetails");
var rowLength = table.rows.length;
for (var i = 0; i < rowLength; i += 1) {
var row = table.rows[i];
var cell = row.cells[10].innerHTML;
}
This gets:
<input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Vat" value="0" type="hidden">0
How can I get the value (=0) from this?
JQuery:
$("#tbInvoiceDetails tr").each(function () {
//Code
}
This simply does not work. I have tried every combination I can think of inside the "" and nothing works.
Table HTML with One Line:
<tbody id="tbInvoiceDetails">
<tr id="trInvoiceDetail0">
<td style="display:none">
<input name="InvoiceDetails.Index" value="0" type="hidden"></td>
<td style="display:none"><input name="InvoiceDetails[0].id" value="-1" type="hidden"></td>
<td style="display:none"><input name="InvoiceDetails[0].InvoiceId" value="0" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].LineTypeId" value="1" type="hidden">1</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].AllocationCodeId" value="19" type="hidden">2030 6016750 KQ73020394 11014008</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].GspId" value="" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].RunTypeId" value="" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].BillingPeriodFromDate" value="06/08/2015" type="hidden">06/08/2015</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].BillingPeriodToDate" value="19/08/2015" type="hidden">19/08/2015</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Net" value="9999" type="hidden">9999</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Vat" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].InterestPay" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].InterestReceiveable" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].VatCodeId" value="8" type="hidden">8</td>
<td><input class="btn" id="btnRemoveInvoiceDetail" value="Remove" onclick="removeRow(0);" type="button"></td>
</tr>
</tbody>
Going the by-column-position route:
jQuery:
$('#tbInvoiceDetails tr td:nth-child(11) input').each(
function() {
var val = this.value;
console.log(val);
}
);
Pure JS:
var table = document.getElementById("tbInvoiceDetails");
var rowLength = table.rows.length;
for (var i = 0; i < rowLength; i += 1) {
var input = table.rows[i].cells[10].firstElementChild;
var val = input.value;
console.log(val);
}

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