Select only checkboxes that are checked in a column - javascript

I have an html table that has 5 columns. 2 columns are checkboxes (entry and high) and the other 3 are data. I have 2 buttons, one is called entry and the other high. When a user clicks on the high button, I'm trying to check the column (high) only and get all that is checked, take those values and average them.
The same with entry, when the entry button is clicked, check only the checkboxes in column (entry) and take those values and average them.
So far I have a function to check both columns but not sure how to separately check and separate the columns to each button function only. I have tried the below, but the GetHigh function doesn't work.
Any points in the right direction would be appreciated!
Table
<td><input type="checkbox" class="entry" id="entry" value="{{$sup->entry}}" name="rows[]"></td>
<td><input type="checkbox" class="high" id="high" value="{{$sup->high}}" name="rows[]"></td>
<td><span style="color: #007E33">{{$sup->entry}} </span></td>
<td><span style="color: #007E33">{{$sup->high}} </span></td>
<td><span style="color: #007E33">{{$sup->days}} </span></td>
Buttons
<a href="#here" class="btn btn-primary btn-pill w-10" id="entry" onclick="GetEntry()">
Entry Average
</a>
<a href="#here" class="btn btn-primary btn-pill w-10" id="high" onclick="GetHigh()">
High Average
</a>
Javascript
function GetEntry() {
//Create an Array.
var selected = new Array();
//Reference the Table.
var supTable = document.getElementById("supTable");
//Reference all the CheckBoxes in Table. I WANT ONLY THE ENTRY COLUMN
var entry = supTable.getElementsByTagName("INPUT");
// Loop and push the checked CheckBox value in Array.
for (var i = 0; i < entry.length; i++) {
if (entry[i].checked) {
selected.push(entry[i].value);
}
}
// alert("Average: " + calculate(selected));
$(".text-message").text("Average: " + calculate(selected)).show();
}
function GetHigh() {
//Create an Array.
var selected = new Array();
//Reference the Table.
var supTable = document.getElementById("supTable");
//Reference all the CheckBoxes in Table. I WANT ONLY THE ENTRY COLUMN
var entry = supTable.getElementsByName("High");
// Loop and push the checked CheckBox value in Array.
for (var i = 0; i < high.length; i++) {
if (high[i].checked) {
selected.push(high[i].value);
}
}
// alert("Average: " + calculate(selected));
$(".text-message").text("Average: " + calculate(selected)).show();
}

getElementsByName is used to select HTML where their name="" attribute matches what you've entered, in this case 'High'. But your HTML in the example shows a different name.
You want to use querySelectorAll('high') to get all of the elements that have class="high" set.

You can use a css selector to get the cells of your table
const getCheckboxes = columnIndex =>document.querySelectorAll(`tbody td:nth-child(${columnIndex}) input:checked`);
Or add a common class and select by the class to the checkboxes
const getCheckboxes = className =>document.querySelectorAll(`tbody .${className}:checked`);
Basic example:
const getCheckedCheckboxesClassName = className => document.querySelectorAll(`tbody .${className}:checked`);
const getCheckedCheckboxesByIndex = columnIndex =>document.querySelectorAll(`tbody td:nth-child(${columnIndex}) input:checked`);
const sumValues = cbs => [...cbs].reduce((total, cb) => total + +cb.value, 0);
const getTotal = (group) => {
const cbs = getCheckedCheckboxesClassName(group);
const value = sumValues(cbs);
console.log(value);
}
const getTotalIndex = (index) => {
const cbs = getCheckedCheckboxesByIndex(index);
const value = sumValues(cbs);
console.log(value);
}
<button type="button" onclick="getTotal('low'); getTotalIndex(1)">low</button>
<button type="button" onclick="getTotal('high'); getTotalIndex(2)">high</button>
<table>
<tbody>
<tr>
<td><input class="low" type="checkbox" value="1" /></td>
<td><input class="high" type="checkbox" value="10" /></td>
</tr>
<tr>
<td><input class="low" type="checkbox" value="2" /></td>
<td><input class="high" type="checkbox" value="20" /></td>
</tr>
<tr>
<td><input class="low" type="checkbox" value="3" /></td>
<td><input class="high" type="checkbox" value="30" /></td>
</tr>
<tr>
<td><input class="low" type="checkbox" value="4" /></td>
<td><input class="high" type="checkbox" value="40" /></td>
</tr>
<tr>
<td><input class="low" type="checkbox" value="5" /></td>
<td><input class="high" type="checkbox" value="50" /></td>
</tr>
</tbody>
</table>

Related

Sum of <td> value from dynamic generated table based on checkbox attribute

I have been trying to find the sum of balance (column) of the selected checkbox as below
HTML
<h2>Sum of selected invoices is AED <div class="totalsum"></div></h2>
<table border="1" id="rcpt"><tr><th><input type="checkbox" onClick="selectAll(this),updateSum()" /></th><th>Invoice No.</th><th>Date</th><th>Balance</th></tr>
<tr>
<td><input type="checkbox" class="checkbox" name="select[]" value="2" onclick="updateSum()" /></td>
<td>INV-2020-0001</a></td>
<td>31-05-2020</td>
<td class="balance">56,842.50</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox" name="select[]" value="3" onclick="updateSum()" /></td>
<td>INV-2020-0002</a></td>
<td>10-06-2020</td>
<td class="balance">96,962.60</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox" name="select[]" value="4" onclick="updateSum()" /></td>
<td>INV-2020-0003</a></td>
<td>15-06-2020</td>
<td class="balance">100,251.20</td>
</tr>
</table>
PHP (Edit)
<?php
$query = 'QUERY';
$sql = mysqli_query($conn, $query);
while ($result = mysqli_fetch_array($sql)) {
$id = $result['id'];
$inv_no =$result['cinv_no'];
$inv_date = $result['cinv_date'];
$inv_bal = $result['cinv_bal'];
echo '<tr>';
echo '<td><input type="checkbox" class="checkbox" name="select[]" value="'.$id.'" onclick="updateSum()" /></td>';
echo '<td>'.$cinv_no.'</a></td>';
echo '<td>'.date("d-m-Y", strtotime($cinv_date)).'</td>';
echo '<td class="balance">'.number_format($cinv_bal,2).'</td>';
echo '</tr>';
}
?>
Javascript (JS + Jquery)
function selectAll(source) {
select = document.getElementsByName('select[]');
for(var i=0, n=select.length;i<n;i++) {
select[i].checked = source.checked;
}
}
function updateSum() {
var total = 0;
var select = $(".checkbox:checked");
var balance = $(".balance");
select.each(function() { total += parseFloat(balance.html().replace(/,/g, ''));})
$(".totalsum").html(total.toFixed(2));
}
Whenever I select a random checkbox, it adds the balance in order(first to last) rather than the selected balances
JSFiddle https://jsfiddle.net/cj19zban/
You need to find the .balance related to the checked checkbox.
function updateSum() {
var total = 0;
var select = $(".checkbox:checked");
select.each(function() {
// get the balance relative to the checked checkbox
const balance = select.parents('tr').find('.balance');
total += parseFloat(balance.html().replace(/,/g, ''));
})
$(".totalsum").text(total.toFixed(2));
}
However, this is somewhat inefficient. I would do something slightly different. You can store the relative balance as the value of the input.. which saves time figuring out which element to get it from.
const updateTotal = () => {
const total = $(".checkbox:checked")
.map((index, checkedCheckbox) => parseFloat(checkedCheckbox.dataset.value))
.toArray()
.reduce((acc, cur) => acc + cur, 0);
$('#totalsum').text(total.toFixed(2));
}
const toggleAll = (checked) => {
$('.checkbox').each((index, checkbox) => {
checkbox.checked = checked;
});
}
$('.checkbox').click(updateTotal);
$('#selectAll').click(function() {
toggleAll($(this).is(':checked'));
updateTotal();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Receipts</h1>
<h2>Sum of selected invoices is AED
<div id="totalsum">0.00</div>
</h2>
<table border="1" id="rcpt">
<tr>
<th><input id='selectAll' type="checkbox" /></th>
<th>Invoice No.</th>
<th>Date</th>
<th>Balance</th>
</tr>
<tr>
<td><input type="checkbox" class="checkbox" name="select[]" value="2" data-value="56842.50" /></td>
<td>INV-2020-0001</td>
<td>31-05-2020</td>
<td class="balance">56,842.50</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox" name="select[]" value="3" data-value="96962.60" /></td>
<td>INV-2020-0002</td>
<td>10-06-2020</td>
<td class="balance">96,962.60</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox" name="select[]" value="4" data-value="100251.20" /></td>
<td>INV-2020-0003</td>
<td>15-06-2020</td>
<td class="balance">100,251.20</td>
</tr>
</table>
I also removed some trailing </a> that seems to break your HTML.

Where do I implement the getElementById in my JavaScript function?

Background: For my website I have to count the number of checked checkboxes in a table. Depending on the result, there is then a different 'output'. As long as fewer than or equal to 2 checkboxes are checked --> output A. If more than 2 boxes are checked OR the first checkbox is checked --> output B.
Now to my problem: I specifically don't understand this line of code:
const checked = [...this.querySelectorAll(".choice:checked")].map(inp => +inp.value);
If I understand correctly, it checks all input fields in the form, adds and converts the results. But how can I implement an ID here that I only give to the first checkbox in order to solve the problem?
And another question: Can I then link the values ​​with a logical operator?
My code:
.hide {
display: none;
}
<form id="listForm">
<table>
<tbody>
<tr id="G">
<td><b>G</b></td>
<td></td>
<td><input type="checkbox" class="choice" id="cbg" name="choiceG" value="1"></td>
</tr>
<tr>
<td id="A"><b>A</b></td>
<td></td>
<td><input type="checkbox" class="choice" name="choiceA" value="1"></td>
</tr>
<tr>
<td id="B"><b>B</b></td>
<td></td>
<td><input type="checkbox" class="choice" name="choiceB" value="1"></td>
</tr>
<tr>
<td id="C"><b>C</b></td>
<td></td>
<td><input type="checkbox" class="choice" name="choiceC" value="1"></td>
</tr>
<tr>
<td colspan="2" ;="" style="text-align:right;"><b>Sum:</b></td>
<td><input disabled="" type="text" size="2" name="total" id="total" value="0"></td>
</tr>
</tbody>
</table>
</form>
<div id="showwhen2" class="hide">
<p>2 or less boxes checked; first box is unchecked</p>
</div>
<div id="showwhen3" class="hide">
<p>first box or more than two boxes are checked</p>
</div>
<script>
document.getElementById("listForm").addEventListener("input", function() {
let sum = 0;
let sumg = 0;
const checked = [...this.querySelectorAll(".choice:checked")].map(inp => +inp.value);
const checkedg = [...this.querySelectorAll(".choice:checked")].map(inp => +inp.value);
if (checked.length > 0) sum = checked.reduce((a, b) => a + b);
if (checkedg.length > 0) sumg = checkedg.reduce((a, b) => a + b);
console.log(sum);
console.log(sumg);
document.getElementById("total").value = sumg + sum;
document.getElementById("showwhen3").classList.toggle("hide", sum < 3 || sumg <1);
document.getElementById("showwhen2").classList.toggle("hide", sum > 2);
});
</script>
This seems really overcomplicated.
const checkedCount = this.querySelectorAll(".choice:checked").length
if (checkedCount > 2 || this.querySelector('input#cbg').checked) {
//output B
} else {
//output A
}
querySelectorAll returns a list of all elements that match the selector (i. e. all checked inputs) and querySelector just one element. # is selector syntax for element ids.

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

How to get values of dynamically created input fields (Json)

input fields are created via jquery depend on user input
If user type Quantity : 5 then i m created 5 input fields
for example if user give Quantity = 3 then this is how the html created dynamically using Jquery
<tr id = "tr_1">
<td><input type="text" name="cont_no1" id="cont_no1" /><td>
<td><input type="text" name="cont_size1" id="cont_size1" /><td>
<td><input type="text" name="cont_type1" id="cont_type1" /><td>
</tr>
<tr id = "tr_2">
<td><input type="text" name="cont_no2" id="cont_no1" /><td>
<td><input type="text" name="cont_size2" id="cont_size2" /><td>
<td><input type="text" name="cont_type2" id="cont_type2" /><td>
</tr>
<tr id = "tr_3">
<td><input type="text" name="cont_no3" id="cont_no3" /><td>
<td><input type="text" name="cont_size3" id="cont_size3" /><td>
<td><input type="text" name="cont_type3" id="cont_type3" /><td>
</tr>
now i need to store all this input fields values in json.
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
i tried like this but its not working the please someone help me. ThankYou
for your refrence here is full code, var auto_tr value is aligned here(with enter) for your purpose .
$(document).ready(function(){
$( "#cont_qty" ).change(function()
{
var itemCount = 0;
$("#munna").empty();
var cont_qty = this.value;
for(var i=0 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'">
<td>
<input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value="">
</td>
<td>
<select class="input-mini" name="cont_size'+itemCount+'" id="cont_size'+itemCount+'">
<option>20</option>
<option>40</option>
<option>45</option>
</select>
</td>
<td>
<select class="input-mini" name="cont_type'+itemCount+'" id="cont_type'+itemCount+'">
<option>DV</option>
<option>HD</option>
<option>HC</option>
<option>OT</option>
<option>FR</option>
<option>HT</option>
<option>RF</option>
</select>
</td>
<td>
<select class="input-medium" name="cont_tonnage'+itemCount+'" id="cont_tonnage'+itemCount+'">
<option>24000 Kgs</option>
<option>27000 Kgs</option>
<option>30480 Kgs</option>
<option>Super Heavy Duty</option>
</select>
</td>
<td>
<input class="input-medium" type="text" id="cont_tare'+itemCount+'" name="cont_tare'+itemCount+'" value="">
</td>
<td>
<input class="input-medium" name="cont_netweight'+itemCount+'" id="cont_netweight'+itemCount+'" type="text" value="">
</td>
<td>
<input class="input-mini" name="yom'+itemCount+'" id="yom'+itemCount+'" type="text" value=""></td>
<td>
<select class="input-medium" name="cont_condition'+itemCount+'" id="cont_condition'+itemCount+'">
<option>IICL</option>
<option>ASIS</option>
<option>CARGO WORTHY</option>
</select>
</td>
</tr>';
$("#munna").append(auto_tr);
}
});
$("#getButtonValue").click(function ()
{
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty.value; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
alert(jsonObj[0].cont_no[1]);
});
});
did small loop mistake :)
for(var i=1; i<=cont_qty.value; i++)
{
alert(cont_qty.value);
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
in previous one i<cont_qty.value this one used now just changed as i<=cont_qty.value
so the loop ran 3 times when qty is 4. now just added <=
ThankYou for your answers friends
Make sure you call your function after you created the html via jquery.
createHtml(); // function to create the html
storeValuesToArray(); // Your function to store data to array
Also make sure you properly close your tags <tr></tr>. And put <tr> inside a <table> tag.
And make sure your cont_qty is set to a value
After you created the html and added all the fields necessary, you can catch all elements by using a selector like:
var jsonObj= jsonObj || [];
$('[name^="cont_no"]').each(function(){
var i = this.name.split('cont_no')[1];
var item = {};
item['cont_no'] = $(this).val();
item['cont_size'] = $('[name="cont_size'+i+'"]').val();
item['cont_type'] = $('[name="cont_type'+i+'"]').val();
jsonObj.push(item);
});

Iterating through table and get the value of a button in each tablerow jQuery

I have buttons in a table which are created dynamically. I want to iterate through a table, get the tablerows which contain a checked checkbox and get the value of a button inside the tablerow. I want to push the values in an array after. The buttons don't have a unique ID so I cannot get their values by id.
I tried to get the values through giving the buttons a class and itering works fine but the array is filled with empty entries.
$("#bt_multiple_deletion").off().on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).find(".filefolder-button").text());
});
})
I really don't know what Im doing wrong. I tried to get the values with .text(), .val() etc.
My table row looks like this:
<tr class="select">
<td>
<span class="countEntries"><input id="lv_fifo_ctrl7_cb_delete_file" type="checkbox" name="lv_fifo$ctrl7$cb_delete_file" /></span>
</td>
<td>
<img src="images/icons/013_document_02_rgb.png" alt="document" />
</td>
<td class="name">//the button i want to get the value from
<input type="submit" name="lv_fifo$ctrl7$bt_file" value="013_document_png.zip" id="lv_fifo_ctrl7_bt_file" class="filefolder-button download file del" style="vertical-align: central" />
</td>
<td>
<span id="lv_fifo_ctrl7_lb_length">33.14 KB</span>
</td>
<td>
<span id="lv_fifo_ctrl7_lb_CreationTime">21.10.2014 07:34:46</span>
</td>
<td></td>
<td>
<input type="submit" name="lv_fifo$ctrl7$bt_del_file" value="delete" id="lv_fifo_ctrl7_bt_del_file" class="delete-button delete-file" />
</td>
</tr>
The problem is rows is the input elements not the tr elements so in the loop you need to find the tr which contains the input then find the target element inside it
$("#bt_multiple_deletion").off().on("click", function () {
var checked = $(".select").find("input[type=checkbox]:checked");
var files = checked.map(function () {
return $(this).closest('tr').find(".filefolder-button").val();
}).get();
})
Another option is
$("#bt_multiple_deletion").off().on("click", function () {
var rows = $(".select").find("tr").has('input[type=checkbox]:checked');
//var rows = $(".select").find('input[type=checkbox]:checked').closest('tr');
var files = rows.map(function () {
return $(this).find(".filefolder-button").val();
}).get();
})
#Timo Jokinen Do you need this
$("#bt_multiple_deletion").on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).parents("tr").find("td.filefolder-button").text());
});
console.log(files);
})
<table class="select">
<tr>
<td class="filefolder-button">test1</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test2</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test3</td>
<td><input type="checkbox" /></td>
</tr>
</table>
<button id="bt_multiple_deletion">delete</button>
Checkout example link here

Categories

Resources