JavaScript checkbox validation in table - javascript

I have designed a table below using HTML. I have validated for only one row, but for the 2nd row it was not validated. Below UI have given submit that validates entire table.
Condition is that at least one checkbox should be selected from each row.

Using pure js: https://jsfiddle.net/v8mghww9/1/
function validate(form)
{
var rows = document.getElementsByTagName('tr');
var isTableValid = true;
for(var i=0;i<rows.length;i++) {
var checkboxs=rows[i].getElementsByTagName("input");
var okay=false;
for(var j=0;j<checkboxs.length;j++)
{
console.log('here' + checkboxs[j].checked);
if(checkboxs[j].checked)
{
okay=true;
break;
}
}
if(!okay && checkboxs.length > 0) {
isTableValid = false;
break;
}
}
if(isTableValid)
return true;
else
{
alert("Please select atleast one item for male patients");
return false;
}
}

Your code was fine but you weren't writing the jsfiddle the right way, this is a live snippet showing that your code works fine:
function validate(form) {
var checkboxs = document.getElementsByName("m1");
var okay = false;
for (var i = 0, l = checkboxs.length; i < l; i++) {
if (checkboxs[i].checked) {
okay = true;
break;
}
}
if (okay) return true;
else {
alert("Please select atleast one item for male patients");
return false;
}
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
padding: 0.5em;
line-height: 1.5em;
}
#color {
background-color: lightblue;
}
.adjust {
text-align: left;
}
input[type="checkbox"] {
margin-left: 47%;
}
<table border="1" width="100%">
<tr>
<th rowspan="3">OAB Patient Types</th>
<th colspan="6" id="color">Therapy of First Choice</th>
</tr>
<tr>
<th colspan="4" id="color">Muscarinic Antagonists</th>
<th style="background-color:lightblue">Beta-3 Adrenergic Agonist</th>
<th style="background-color:lightblue">Other Therapies</th>
</tr>
<tr>
<th>Detrol LA
<br>(tolterodine)</th>
<th>Enablex
<br>(darifencian)</th>
<th>Toviaz
<br>(festoridine)</th>
<th>VESIcare
<br>(solifencian)</th>
<th>Myrbetriq
<br>(merabergan)</th>
<th>Other</th>
</tr>
<tr>
<th colspan="7" id="color" class="adjust">General Patient Types</th>
</tr>
<tr>
<td>Male Patients</td>//
<form name=form1>
<td>
<input type="checkbox" name=m1>
</td>
<td>
<input type="checkbox" name=m1>
</td>
<td>
<input type="checkbox" name=m1>
</td>
<td>
<input type="checkbox" name=m1>
</td>
<td>
<input type="checkbox" name=m1>
</td>
<td>
<input type="checkbox" name=m1>
</td>//</form>
</tr>
<tr>
<td>Female Patients</td>
<form name=form2>
<td>
<input type="checkbox" name=f1>
</td>
<td>
<input type="checkbox" name=f1>
</td>
<td>
<input type="checkbox" name=f1>
</td>
<td>
<input type="checkbox" name=f1>
</td>
<td>
<input type="checkbox" name=f1>
</td>
<td>
<input type="checkbox" name=f1>
</td>
<!-- <td><input type="submit" value="submit"></td> -->
</form>
</tr>
<tr>
<th colspan="7" id="color" class="adjust">Line of Therapy</th>
</tr>
<tr>
<td>First-line (newly daignosed OAB patients on their first course of therapy)</td>
<form>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
</form>
</tr>
<tr>
<td>Second-line</td>
<form>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
</form>
</tr>
<tr>
<td>Third-line</td>
<form>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
<td>
<input type="checkbox">
</td>
</form>
</tr>
</table>
<br>
<br>
<center>
<input type="button" value="Submit" onclick='return validate()'>
</center>
Note:
The button Submit should be of type button and not submit.
First thing because it's not inside any form to be submitted
Second thing is that you have many forms in your page (which is strange here), so you may have a conflict in submitting which form of them wityh this submit button?

give the same name on all the checkboxes of each row and then give it a class to all which you want to validate.
function validate() {
var flag = true;
var array = [];
$(".js-validate-required-radio").each(function () {
array.push($(this).prop('name'));
});
var uniqueNames = $.unique(array);
for (var i = 0; i < uniqueNames.length; i++) {
if ($('input:checkbox[name=' + uniqueNames[i] + ']:checked').val() == undefined) {
if (flag) {
flag = false;
}
}
}
if(!flag){
alert('select atleast one radio on each row');
}
else{
alert('yeee');
}
return flag;
}
here is fiddle

Related

When a Radio Button is Unchecked, Hide its Connected Element

I'm sorry, the title is awkward. Basically I'm using onclick() to show/hide different elements. When I click Radio1, it shows the element, but when I click Radio2 it doesn't hide Radio1's element, and vice versa. The only way I can think of doing it is doing a manual if statement, like so:
function RadioCheck(id) {
if (id == 'Radio1') {
document.getElementById(id).style.display = "table-row-group";
document.getElementById('Radio2').style.display = "none";
} else if (id == 'Radio2') {
document.getElementById(id).style.display = "table-row-group";
document.getElementById('Radio1').style.display = "none";
}
}
But when I have to do that for 5 radio buttons, it gets messy and gaudy. I'm not sure how to go about making it so the other elements will hide.
I've tried checking if the the radio with the corresponding is checked/unchecked, to hide/show it. But that doesn't work because obviously once you pass through another parameter, the previous one won't work
I've Googled and can't find it.
Edit: Here's the relevant HTML
Radio HTML
<tr>
<td>
<span class="label">Platform:</span>
</td>
<td>
<input type="radio" name="platform" onclick="RadioCheck('Radio1');">Radio1</input>
<input type="radio" name="platform" onclick="RadioCheck('Radio2');">Radio2</input>
<input type="radio" name="platform" onclick="RadioCheck('Radio3');">Radio3</input>
<input type="radio" name="platform" onclick="RadioCheck('Radio4');">Radio4</input>
<input type="radio" name="platform" onclick="RadioCheck('Radio5');">Radio5</input>
</td>
</tr>
Radio1 HTML:
<tr id="Radio1">
<td>
<span class="label">Limited State:</span>
</td>
<td>
<input type="radio" value="Y" id="limStatY" name="limStat">Y</input>
<input type="radio" value="N" id="limStat" name="limStat" checked="true">N</input>
</td>
</tr>
Radio2 HTML:
<tbody id="Radio2">
<tr>
<td>
Locked to Sector?
</td>
<td>
<input type="radio" name="sectorLock" >Yes</input>
<input type="radio" name="sectorLock" >No</input>
</td>
</tr>
<tr>
<td>
<span class="label">Tech Alert</span>
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
<tr>
<td>
Alerts Portal
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
<tr>
<td>
Reason for Call
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
<tr>
<td>
What exactly is not working?
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
<tr>
<td>
Describe specific web service
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
</tbody>
And I have my CSS to start the elements off hidden:
#Radio1 {
display: none;
}
#Radio2 {
display: none;
}
You can simply hide everything and then display one instead of adding logic to hide everything except the one that is about to be displayed.
function RadioCheck(id)
{
// Hide all
document.getElementById('Radio1').style.display = "none";
document.getElementById('Radio2').style.display = "none";
document.getElementById('Radio3').style.display = "none";
document.getElementById('Radio4').style.display = "none";
document.getElementById('Radio5').style.display = "none";
// Display one
document.getElementById(id).style.display = "table-row-group";
}
Here's a method that uses event listeners rather than inline onclick, also uses values for your radios to determine which TR's to show/hide. This example only has content for the first two radios but is extendable for as many as you want.
document.addEventListener('DOMContentLoaded', () => {
let radios = document.querySelectorAll('.tr-toggle-radios input[type=radio]')
let toggled = document.querySelectorAll('.tr-toggle-content')
radios.forEach(el => {
el.addEventListener('change', e => {
toggled.forEach(tog => tog.classList.add('hide'));
document.querySelector(`#${e.target.value}`).classList.remove('hide')
})
})
})
.hide {
display: none;
}
.tr-toggle-content {
display: table-row-group;
}
<table>
<tr>
<td>
<span class="label">Platform:</span>
</td>
<td class='tr-toggle-radios'>
<input type="radio" name="platform" value="Radio1">Radio1</input>
<input type="radio" name="platform" value="Radio2">Radio2</input>
<input type="radio" name="platform" value="Radio3">Radio3</input>
<input type="radio" name="platform" value="Radio4">Radio4</input>
<input type="radio" name="platform" value="Radio5">Radio5</input>
</td>
</tr>
<tr class='tr-toggle-content hide' id="Radio1">
<td>
<span class="label">Limited State:</span>
</td>
<td>
<input type="radio" value="Y" id="limStatY" name="limStat">Y</input>
<input type="radio" value="N" id="limStat" name="limStat" checked="true">N</input>
</td>
</tr>
<tbody class='tr-toggle-content hide' id="Radio2">
<tr>
<td>
Locked to Sector?
</td>
<td>
<input type="radio" name="sectorLock">Yes</input>
<input type="radio" name="sectorLock">No</input>
</td>
</tr>
<tr>
<td>
<span class="label">Tech Alert</span>
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
<tr>
<td>
Alerts Portal
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
<tr>
<td>
Reason for Call
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
<tr>
<td>
What exactly is not working?
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
<tr>
<td>
Describe specific web service
</td>
<td>
<input type="text" style="width: 100%"></input>
</td>
</tr>
</tbody>
</table>
Try this: You keep an array of radio IDs and loop through them when a user interacts with a radio. Then you display the checked radio and hide all the others.
const radio = ['Radio1', 'Radio2', 'Radio3'];
function RadioCheck(id) {
radio.forEach((item) => {
if(id === item){
document.getElementById(id).style.display = "table-row-group";
}else{
document.getElementById(item).style.display = "none";
}
});
}

implementing innerHTML to display output by using form

im planning to display my output thru innerHTML but the javascript cant seem to display my input just like i wanted. when user enter input into the form, i want to display the input by using innerHTML.
my attempt output is just in a normal list similar to something like this:
to students
output 1
output 2
output 3
to organizer
k1
k2
k5
<html>
<head>
<title>part b</title>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<form onsubmit="printChecked()">
<table>
<tr>
<th colspan="2">
activities
</th>
</tr>
<tr>
<td colspan="2">
list 3 kind of activities that you interest
</td>
</tr>
<tr>
<td>
1. to students
</td>
<td>
<textarea name = "pelajar1" rows = "4" cols = "110"></textarea>
<textarea name = "pelajar2" rows = "4" cols = "110"></textarea>
<textarea name = "pelajar3" rows = "4" cols = "110"></textarea>
</td>
</tr>
<tr>
<td>
TO ORGANIZER
</td>
<td>
<input type="checkbox" name="kl" value="communication">K1
<br>
<input type="checkbox" name="kl" value="problems">K2
<br>
<input type="checkbox" name="kl" value="teamwork">K3
<br>
<input type="checkbox" name="kl" value="info">K4
<br>
<input type="checkbox" name="kl" value="business">K5
<br>
<input type="checkbox" name="kl" value="ethics">K6
<br>
<input type="checkbox" name="kl" value="leadership">K7
<br>
</td>
</tr>
</table>
<br><br>
<input type="Submit" value="Submit">
</form>
<script>
function printChecked()
{
var pel1 = document.getElementsByName('pelajar1');
var pel2 = document.getElementsByName('pelajar2');
var pel3 = document.getElementsByName('pelajar3');
var items=document.getElementsByName('kl');
var selectedItems="";
for(var i=0; i<items.length; i++){
if(items[i].type=='checkbox' && items[i].checked==true)
selectedItems+=items[i].value+"\n";
}
document.getElementsByName("pelajar1").innerHTML = pel1;
document.getElementsByName("pelajar2").innerHTML = pel2;
document.getElementsByName("pelajar3").innerHTML = pel3;
document.getElementsByName("kl").innerHTML = items;
}
</script>
</body>
</html>
try this and see console
<html>
<head>
<title>part b</title>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<form>
<table>
<tr>
<th colspan="2">activities</th>
</tr>
<tr>
<html>
<head>
<title>part b</title>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<form onsubmit="printChecked">
<table>
<tr>
<th colspan="2">activities</th>
</tr>
<tr>
<td colspan="2">
list 3 kind of activities that you
interest
</td>
</tr>
<tr>
<td>1. to students</td>
<td>
<textarea
id="pelajar1"
rows="4"
cols="110"
></textarea>
<textarea
id="pelajar2"
rows="4"
cols="110"
></textarea>
<textarea
id="pelajar3"
rows="4"
cols="110"
></textarea>
</td>
</tr>
<tr>
<td>TO ORGANIZER</td>
<td>
<br />
<input
type="checkbox"
id="k1"
value="communication"
/>K1
<input
type="checkbox"
id="k2"
value="problems"
/>K2
<br />
<input
type="checkbox"
id="k3"
value="teamwork"
/>K3
<br />
<input
type="checkbox"
id="k4"
value="info"
/>K4
<br />
<input
type="checkbox"
id="k5"
value="business"
/>K5
<br />
<input
type="checkbox"
id="k6"
value="ethics"
/>K6
<br />
<input
type="checkbox"
id="k7"
value="leadership"
/>K7
<br />
</td>
</tr>
</table>
<br /><br />
<input
type="button"
onclick="printChecked()"
value="Submit"
/>
</form>
<div id="form"></div>
<script>
function printChecked() {
var pel1 =
document.getElementById("pelajar1");
var pel2 =
document.getElementById("pelajar2");
var pel3 =
document.getElementById("pelajar3");
var items = [];
for (let i = 0; i < 7; i++) {
var a = document.getElementById(
"k" + (i + 1),
);
a.checked ? items.push(a.value) : null;
}
console.log(
"1 : " +
pel1.value +
"\n2 :" +
pel2.value +
"\n3 :" +
pel3.value,
);
items.forEach((element) => {
console.log(element);
});
}
</script>
</body>
</html>
</tr>
</table>
</form>
</body>
</html>
Okay i am not so clear about what you want to achieve in here, i believe you want the form submit not to do submission and get the details in the function for some kind of computation , i use this as for a javascript approach for preventing default form submit
make use of a return function that returns false stating not to submit the form as in below example
if this satisfies your query, please refer=>
function printChecked() {
var pel1 = document.getElementsByName('pelajar1');
var pel2 = document.getElementsByName('pelajar2');
var pel3 = document.getElementsByName('pelajar3');
var items = document.getElementsByName('kl');
var selectedItems = "";
for (var i = 0; i < items.length; i++) {
if (items[i].type == 'checkbox' && items[i].checked == true)
selectedItems += items[i].value + "\n";
}
console.log("pel1-data=> "+pel1[0].value);
console.log("pel2-data=> "+pel2[0].value);
console.log("pel3-data=> "+pel3[0].value);
console.log("checkbox-data=> "+selectedItems);
return false;
}
table,
th,
td {
border: 1px solid black;
}
<form onsubmit="return printChecked()">
<table>
<tr>
<th colspan="2">
activities
</th>
</tr>
<tr>
<td colspan="2">
list 3 kind of activities that you interest
</td>
</tr>
<tr>
<td>
1. to students
</td>
<td>
<textarea name="pelajar1" rows="4" cols="110"></textarea>
<textarea name="pelajar2" rows="4" cols="110"></textarea>
<textarea name="pelajar3" rows="4" cols="110"></textarea>
</td>
</tr>
<tr>
<td>
TO ORGANIZER
</td>
<td>
<input type="checkbox" name="kl" value="communication">K1
<br>
<input type="checkbox" name="kl" value="problems">K2
<br>
<input type="checkbox" name="kl" value="teamwork">K3
<br>
<input type="checkbox" name="kl" value="info">K4
<br>
<input type="checkbox" name="kl" value="business">K5
<br>
<input type="checkbox" name="kl" value="ethics">K6
<br>
<input type="checkbox" name="kl" value="leadership">K7
<br>
</td>
</tr>
</table>
<br><br>
<input type="Submit" value="Submit">
</form>
you can see return for onsubmit of form which gets value from the function printChecked() -> see last return statement in function
Additional
for jquery inside the called function definition we can just add the received event's preventDefault function
$("form").submit(function(event){
event.preventDefault();
});
Edit-> prints data on the same page using innerHtml
function printChecked() {
var pel1 = document.getElementsByName('pelajar1');
var pel2 = document.getElementsByName('pelajar2');
var pel3 = document.getElementsByName('pelajar3');
var items = document.getElementsByName('kl');
var selectedItems = "";
for (var i = 0; i < items.length; i++) {
if (items[i].type == 'checkbox' && items[i].checked == true)
//selectedItems += items[i].value + "\n";
//add values as li elements
selectedItems += '<li>'+ items[i].value + '</li>';
}
//show list on submit
document.getElementById("toStudents").style.display = "block";
document.getElementById("toOrganizer").style.display = "block";
//add tostudents text area values in to list
document.getElementById("pelajar1").innerHTML=pel1[0].value;
document.getElementById("pelajar2").innerHTML=pel2[0].value;
document.getElementById("pelajar3").innerHTML=pel3[0].value;
//add toorganizer checkbox values in to list
document.getElementById("toOrganizer").innerHTML=selectedItems;
//just printing values in console
//console.log("pel1-data=> "+pel1[0].value);
//console.log("pel2-data=> "+pel2[0].value);
//console.log("pel3-data=> "+pel3[0].value);
//console.log("checkbox-data=> "+selectedItems);
return false;
}
table,
th,
td {
border: 1px solid black;
}
/*list is hidden at first*/
#toStudents,#toOrganizer{
display:none;
list-style:none;
}
<form onsubmit="return printChecked()">
<table>
<tr>
<th colspan="2">
activities
</th>
</tr>
<tr>
<td colspan="2">
list 3 kind of activities that you interest
</td>
</tr>
<tr>
<td>
1. to students
</td>
<td>
<textarea name="pelajar1" rows="4" cols="110"></textarea>
<textarea name="pelajar2" rows="4" cols="110"></textarea>
<textarea name="pelajar3" rows="4" cols="110"></textarea>
</td>
</tr>
<tr>
<td>
TO ORGANIZER
</td>
<td>
<input type="checkbox" name="kl" value="communication">K1
<br>
<input type="checkbox" name="kl" value="problems">K2
<br>
<input type="checkbox" name="kl" value="teamwork">K3
<br>
<input type="checkbox" name="kl" value="info">K4
<br>
<input type="checkbox" name="kl" value="business">K5
<br>
<input type="checkbox" name="kl" value="ethics">K6
<br>
<input type="checkbox" name="kl" value="leadership">K7
<br>
</td>
</tr>
</table>
<br><br>
<input type="Submit" value="Submit">
<h2>To Students</h2>
<ul id="toStudents">
<li id="pelajar1"></li>
<li id="pelajar2"></li>
<li id="pelajar3"></li>
</ul>
<h2>To Organizer</h2>
<ul id="toOrganizer">
</ul>
</form>
the issue you seem to be experiencing is from the page reloading on the form submit BEFORE the JS function is called. Based on your code, you are calling printChecked() onsubmit when the button is clicked.
To fix your issue, look into Stop form refreshing page on submit, which, among other things, would involve adding return false to your onsubmit call. Other solutions from the same page mention not using button type="submit", and instead focusing on using the type="button" with a separate call from there onclick.
Hopefully this helps!

Count how many are checked from generated checkbox

I'm working on a simple table that generates number of checkbox, and count the total of how many are checked.
when I unchecked, it will show how many are the remaining checked checkbox.
my problem is when I generate new rows the counter doesn't work anymore.
$('.items').keyup(function() {
var items = $(this).val();
$('span').text(items);
$('table tbody tr').remove();
for (var i = 1; i <= items; i++) {
$('table > tbody').append('<tr><td><input type="checkbox" checked></td></tr>');
}
});
$('input:checkbox').click(function() {
var count = $(this).closest('table').find('input:checkbox:checked').length;
$('span').text(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="">
Items
</label>
<input type="text" class="items">
<span>4</span>
<table>
<tbody>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
</tbody>
</table>
Use event delegation instead, so that you only need to apply a single listener to the container, otherwise you'll have to re-add listeners to each element every time:
$('.items').keyup(function() {
var items = $(this).val();
$('span').text(items);
$('table tbody tr').remove();
for (var i = 1; i <= items; i++) {
$('table > tbody').append('<tr><td><input type="checkbox" checked></td></tr>');
}
});
$('table').on('click', 'input', function() {
var count = $(this).closest('table').find('input:checkbox:checked').length;
$('span').text(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="">
Items
</label>
<input type="text" class="items">
<span>4</span>
<table>
<tbody>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
</tbody>
</table>
$('.items').keyup(function() {
var items = $(this).val();
$('span').text(items);
$('table tbody tr').remove();
for (var i = 1; i <= items; i++) {
$('table > tbody').append('<tr><td><input class="checkeboxclass" type="checkbox" checked></td></tr>');
}
});
$('input[type="checkbox"]').on( "change", function() {
var count = $('input[type="checkbox"]:checked').length;
$('span').text(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="">
Items
</label>
<input type="text" class="items">
<span>4</span>
<table>
<tbody>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked>
</td>
</tr>
</tbody>
</table>

Checkbox JavaScript does not update values

I have a table with rows of textboxes as inputs that hold numbers/hours with css .hours. I am trying to get the table to update totals when the row is deleted checkbox is checked/clicked.
How to Update the totals in the row & col at the End? when the delete row checkbox is checked.
2 steps: I zero out the values in the deleted row, and then want to update the new totals.
JS fiddle with HTML
// Call this function, When CheckBox with css .deleteRowis clicked
$('#Maintable').on('click', '.deleteRow', function ()
{
if ($(this).is(":checked")) {
var row = $(this).closest('tr').css({ 'color': 'red' });
var hours = row.find('.hours');
$.each(hours, function (index, item) {
if ($(this).val()) { // if there is a value
$(this).val('0');
// Total the rows does not work??
HoursChangedFunction($(this));
}
});
} // :checked ends
// when the row is deleted from the checkbox, find it and call this function
// 1) First make all .hours 0, 2) and then redo the totals
var HoursChangedFunction = function () {
var columnIndex = $(this).closest('td').index();
var row = $(this).closest('tr');
var hours = row.find('.hours');
var rowTotal = 0;
$.each(hours, function (index, item) {
rowTotal += Number($(this).val());
});
row.children('td.rowtotal').text(rowTotal.toFixed(2));
var columnTotal = 0;
var grandTotal = 0;
var rows = $('#Maintable tr');
$.each(rows, function (index, item) {
columnTotal += Number($(this).children('td').eq(columnIndex).children('.hours').val());
grandTotal += Number($(this).children('.rowtotal').text());
});
footer.eq(columnIndex).text(columnTotal.toFixed(2));
total.text(grandTotal.toFixed(2));
};
Because you have a lot of IDs you may avoid HoursChangedFunction.
In order to get the corresponding cell in the current col you can use the eq method
Moreover, you can use .text( function ) to simplify the task.
You can simplify the event handler from:
$('#Maintable').on('click', '.deleteRow', function ()
to:
$('#Maintable').on('change', '.deleteRow:checked', function () {
because inside the handler you execute the logic only when the checkbox is checked.
The snippet:
$('#Maintable').on('change', '.deleteRow:checked', function () {
var row = $(this).closest('tr').css({'color': 'red'});
$('#grandtotal').text(function(idx, txt) {
return (+txt - +row.find('.rowtotal').text()).toFixed(2);
});
row.find('.rowtotal').text('0.00');
row.find('.hours').each( function (index, item) {
if (item.value != '0.00') {
$('#Maintable').closest('table').find('tfoot tr td').eq(index + 2).text(function(idx, txt) {
return (+txt - +item.value).toFixed(2);
});
item.value = '0.00';
}
});
});
.hours {
width: 50px;
box-sizing: border-box;
border: solid 1px #d9e1e4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Task</th>
<th>Code</th>
<th>day1</th>
<th>day2</th>
<th>dy3</th>
<th>day4</th>
<th>day5</th>
<th>day6</th>
<th>day7</th>
<th>Total</th>
<th>Del</th>
</tr>
</thead>
<tbody id="Maintable">
<tr>
<td>
<span class="project">Project 1</span>
</td>
<td>
<span class="timecode">code 1A</span>
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="2.50">
</td>
<td>
<input class="hours" type="text" value="4.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td class="rowtotal">6.50</td>
<td><input class="bs-checkbox deleteRow" data-val="true" type="checkbox" value="true"></td>
</tr>
<tr>
<td>
<span class="project">Project 2</span>
</td>
<td>
<input type="hidden" name="Records.Index" value="1">
<span class="timecode">code 2B</span>
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="4.50">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td class="rowtotal">4.50</td>
<td><input class="bs-checkbox deleteRow" data-val="true" type="checkbox" value="true"></td>
</tr>
<tr>
<td>
<span class="project">Project 3</span>
</td>
<td>
<span class="timecode">code 2C</span>
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.50">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" ype="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td>
<input class="hours" type="text" value="0.00">
</td>
<td class="rowtotal">0.50</td>
<td><input class="bs-checkbox deleteRow" data-val="true" type="checkbox" value="true"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td>0.00</td>
<td>7.50</td>
<td>4.00</td>
<td>0.00</td>
<td>0.00</td>
<td>0.00</td>
<td>0.00</td>
<td id="grandtotal">11.50</td>
</tr>
</tfoot>
</table>

Get all the values of td columns from table where checkbox is checked

I have a table as below:
..
There have been multiple questions asked for getting the values but in this case I should always have a parent item name. Suppose If a user selected only one subitem in "Shirts", then I should be able to get all the values from the selected tr and with that I need parent item name also i.e "shirts" and if some one clicks on all the subitems of a parent item, then all the values of all tr are need to be in some sort of array object on click of a "Save" button. I am trying hard to do this. Any help would be really appreciated. Though I have attached the HTML but this HTML is being generated at run time.
HTML:
<table>
<tr>
<td> </td>
<td> </td>
<td>Name</td>
<td>Sub Item</td>
<td>User Input</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkGroup1" class="cls1" onclick="checkUncheckAll(this);" />
</td>
<td>Shirts
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item1</td>
<td>SubItem1</td>
<td>
<input id="1datepicker" name="1datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item2</td>
<td>SubItem2</td>
<td>
<input id="2datepicker" name="2datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item3</td>
<td>SubItem3</td>
<td>
<input id="3datepicker" name="3datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkGroup2" class="cls2" onclick="checkUncheckAll(this);" />
</td>
<td>Jeans
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item4</td>
<td>SubItem4</td>
<td>
<input id="4datepicker" name="4datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item5</td>
<td>SubItem5</td>
<td>
<input id="5datepicker" name="5datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item6</td>
<td>SubItem6</td>
<td>
<input id="6datepicker" name="6datepicker" type="text" /><script>
</script></td>
</tr>
</table>
Script code looks like below:
<script>
function checkUncheckAll(sender) {
var chkElements = document.getElementsByClassName(sender.className);
for (var i = 0; i < chkElements.length; i++) {
chkElements[i].checked = sender.checked;
}
}
function CheckCorrespondingHeader(sender) {
ControlLength = $("[name='" + sender.name + "']").length;
var countchecks = 0;
$("[name='" + sender.name + "']").each(function () {
if ($(this).prop('checked') == true) {
countchecks = countchecks + 1;
}
});
if (ControlLength == countchecks) {
$("#chk" + sender.name).attr('checked', 'checked');
}
else {
$("#chk" + sender.name).prop('checked', false);
}
}
function PickAllCheckedRows() {
}
</script>
As far as I can tell your code should work if you fix one issue. You are determining the number of sub rows that need to be checked to make the header row be checked using $("[name='" + sender.name + "']").length;. But unless I'm mistaken sender.name is never set. Of course if you set it this still won't work because your each function will include the header row. There are several solutions to this but I would recommend using a data attribute instead of the name attribute like so:
Markup:
<table>
<tr>
<!-- head -->
<td><input type="checkbox" data-head-for-group="Group1" ... /></td>
</tr>
<tr>
<!-- row 1 -->
<td><input type="checkbox" data-in-group="Group1" ... /></td>
</tr>
<tr>
<!-- row 2 -->
<td><input type="checkbox" data-in-group="Group1" ... /></td>
</tr>
<tr>
<!-- head -->
<td><input type="checkbox" data-head-for-group="Group2" ... /></td>
</tr>
<tr>
<!-- row 3 -->
<td><input type="checkbox" data-in-group="Group2" ... /></td>
</tr>
</table>
Script:
function CheckCorrespondingHeader(sender) {
var group = $("[data-in-group='" + sender.data('headForGroup') + "']");
var groupSize = group.length;
var countchecks = 0;
group.each(function () {
if ($(this).prop('checked') === true) {
countchecks = countchecks + 1;
}
});
if (groupSize === countchecks) {
$(sender).attr('checked', 'checked');
} else {
$(sender).prop('checked', false);
}
}

Categories

Resources