Jquery: Dynamic Loop table by its column and sum - javascript

i have these scenario, i would like to sum the
1) unit x on Table A with unit x on Table B
2) unit y on Table A with unit y on Table B
3) put the sum into Table C by its row index on Table A correspondingly
Below is my code, which is working fine:
Table A:
<table class="tableA" border='1'>
<tbody>
<tr>
<td></td>
<td>JAN</td>
<td>FEB</td>
<td>MAR</td>
</tr>
<tr>
<td>Unit X</td>
<td><input type="text" value="1" class="jan"></td>
<td><input type="text" value="2" class="feb"></td>
<td><input type="text" value="3" class="mar"></td>
</tr>
<tr>
<td>Unit Y</td>
<td><input type="text" value="2" class="jan"></td>
<td><input type="text" value="2" class="feb"></td>
<td><input type="text" value="2" class="mar"></td>
</tr>
</tbody>
</table>
Table B:
<table class="tableB" border='1'>
<tbody>
<tr>
<td></td>
<td>JAN</td>
<td>FEB</td>
<td>MAR</td>
</tr>
<tr>
<td>Unit X</td>
<td><input type="text" value="4" class="jan"></td>
<td><input type="text" value="4" class="feb"></td>
<td><input type="text" value="4" class="mar"></td>
</tr>
<tr>
<td>Unit Y</td>
<td><input type="text" value="5" class="jan"></td>
<td><input type="text" value="5" class="feb"></td>
<td><input type="text" value="5" class="mar"></td>
</tr>
</tbody>
</table>
Table C:
<table class="tableC" border='1'>
<tbody>
<tr>
<td></td>
<td>JAN</td>
<td>FEB</td>
<td>MAR</td>
</tr>
<tr>
<td>Unit X</td>
<td><input type="text" value="" class="jan"></td>
<td><input type="text" value="" class="feb"></td>
<td><input type="text" value="" class="mar"></td>
</tr>
<tr>
<td>Unit Y</td>
<td><input type="text" value="" class="jan"></td>
<td><input type="text" value="" class="feb"></td>
<td><input type="text" value="" class="mar"></td>
</tr>
</tbody>
</table>
Jquery:
$( document ).ready(function() {
$(".tableA").find(".jan").each(function() {
var value_A = $(this).val();
var row_index = $(this).closest("tr").index();
var value_B = $('.tableB').find("tr:eq("+row_index+") .jan").val();
var sum = parseInt(value_A) + parseInt(value_B);
$('.tableC').find("tr:eq("+row_index+") .jan").val(sum);
});
$(".tableA").find(".feb").each(function() {
var value_A = $(this).val();
var row_index = $(this).closest("tr").index();
var value_B = $('.tableB').find("tr:eq("+row_index+") .feb").val();
var sum = parseInt(value_A) + parseInt(value_B);
$('.tableC').find("tr:eq("+row_index+") .feb").val(sum);
});
$(".tableA").find(".mar").each(function() {
var value_A = $(this).val();
var row_index = $(this).closest("tr").index();
var value_B = $('.tableB').find("tr:eq("+row_index+") .mar").val();
var sum = parseInt(value_A) + parseInt(value_B);
$('.tableC').find("tr:eq("+row_index+") .mar").val(sum);
});
});
JSFiddle
Problem: current sum method are hard coded by its classname according to month, example: .jan .feb .mar
How do i do it dynamically to loop by its column without hard coded the classname, because the code will get longer until december.
thanks

The code for each function is generally the same (difference is really just the month. We can make this a generic function. i.e.
const processMonth = function($table, month) {
// Assume month = jan/feb/mar/...
var value_A = $table.val();
var row_index = $table.closest("tr").index();
var value_B = $('.tableB').find("tr:eq("+row_index+") ." + month).val();
var sum = parseInt(value_A) + parseInt(value_B);
$('.tableC').find("tr:eq("+row_index+") ." + month).val(sum);
});
Now we can do something like
// Some months for brevity
const months = ["jan", "feb", "mar", "apr", ... "nov", "dec"];
months.forEach(function(month) {
processMonth($(".tableA"), month);
});

Assuming for each TD has only input[type="text"], then you can do the following. You can use class selector if you want.
$('.tableC input[type="text"]').each(function() {
var indexTR = $(this).closest('tr').index();
var indexTD = $(this).closest('td').index();
var dataA = $('.tableA tr:eq(' + indexTR + ') td:eq(' + indexTD + ') input[type="text"]').val();
var dataB = $('.tableB tr:eq(' + indexTR + ') td:eq(' + indexTD + ') input[type="text"]').val();
var dataC = parseInt(dataA) + parseInt(dataB);
$(this).val(dataC);
});

Related

Check a radio randomly in each row

I have 20 rows in an HTML table, 3 radios in each row. I want randomly to select 1 of the 3 radios in every row.
I have a code snippet, but it does not work properly, because it checks more than 1 radios, or none.
Here is my javascript snippet:
function selectRandomRadioButton(radioButtons) {
const index = Math.floor(Math.random() * radioButtons.length);
const element = radioButtons[index];
element.checked = true;
return `Selected Option ${element.value}`;
}
var table = document.getElementById("randomtable");
var totalRowCount = table.rows.length;
for (let i = 1; i < totalRowCount; i++) {
document.addEventListener("DOMContentLoaded", () => {
const radioButtons = document.getElementsByClassName("random");
const message = selectRandomRadioButton(radioButtons);
console.log(message);
});
}
And here is my html:
<table id="randomtable">
<tr>
<th>#</th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<tr>
<td>1</td>
<td><input type="radio" class="random" /></td>
<td><input type="radio" class="random" /></td>
<td><input type="radio" class="random" /></td>
</tr>
<tr>
<td>2</td>
<td><input type="radio" class="random" /></td>
<td><input type="radio" class="random" /></td>
<td><input type="radio" class="random" /></td>
</tr>
</table>
The table has 21 rows including the first, but I only pasted here 2 for example.

Get total from multiple class onchange

Goodday, i'm trying to get total and grandtotal from textinput . First please check my script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>No</td>
<td>Item</td>
<td>Qty</td>
<td>est</td>
<td>tax</td>
<td>Total</td>
<td>GrandTotal</td>
</tr>
<tr>
<td>No</td>
<td>ITEM 1</td>
<td>2</td>
<td><input type="text" class="est"></td>
<td><input type="text" class="tax"></td>
<td><input type="text" readonly class="total"></td>
<td><input type="text" readonly class="grandtotal"></td>
</tr>
<tr>
<td>No</td>
<td>ITEM 1</td>
<td>2</td>
<td><input type="text" class="est"></td>
<td><input type="text" class="tax"></td>
<td><input type="text" readonly class="total"></td>
<td><input type="text" readonly class="grandtotal"></td>
</tr>
</table>
As you can i see, there is .total and .grandtotal. I want to get it with this
total = .est * .qty
grandtotal = .total * .tax
So, i want to onchange in two fields .est & .tax .
Maybe i can do this
$(document).on("change",".tax",function(){
//Code
});
and
$(document).on("change",".tax",function(){
//Code
});
But it will take time, so i'm trying to approach this way
$(document).on("change",".tax, .est",function(){
//I don't know to get value of .tax or .est only
});
How can i get the total and grandtotal ?
run and see result
$('tr').each(function() {
var qty = $($(this).children()[2]).text(),
$tax = $(this).find(".tax"),
$est = $(this).find(".est"),
$total = $(this).find(".total"),
$grandtotal = $(this).find(".grandtotal")
function onChange() {
var t = $est.val() * qty
var gt = $tax.val() * t
$total.val(t)
$grandtotal.val(gt)
}
$tax.change(onChange)
$est.change(onChange)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>No</td>
<td>Item</td>
<td>Qty</td>
<td>est</td>
<td>tax</td>
<td>Total</td>
<td>GrandTotal</td>
</tr>
<tr>
<td>No</td>
<td>ITEM 1</td>
<td>2</td>
<td><input type="text" class="est"></td>
<td><input type="text" class="tax"></td>
<td><input type="text" readonly class="total"></td>
<td><input type="text" readonly class="grandtotal"></td>
</tr>
<tr>
<td>No</td>
<td>ITEM 1</td>
<td>2</td>
<td><input type="text" class="est"></td>
<td><input type="text" class="tax"></td>
<td><input type="text" readonly class="total"></td>
<td><input type="text" readonly class="grandtotal"></td>
</tr>
</table>
I hope this help
$(function() {
var resultTax = 0, resultEst = 0, total = 0;
$(".tax").change( function() {
$(".tax").each(function() {
resultTax += parseFloat($(this).val())
});
$('.resultTax').text(resultTax);
$('.total').text($('.resultEst').text() + $('.resultTax').text());
});
$(".est").change( function() {
$(".est").each(function() {
resultEst += parseFloat($(this).val())
});
$('.resultEst').text(resultEst);
$('.total').text(parseFloat($('.resultEst').text()) + parseFloat($('.resultTax').text()));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Tax <input type="text" class="tax" value="1">
Tax <input type="text" class="tax" value="2"><br>
Est <input type="text" class="est" value="3">
Est <input type="text" class="est" value="4"><br><br>
resultTax : <span class="resultTax"></span><br>
resultEst : <span class="resultEst"></span><br>
Total Tax + Est : <span class="total"></span>

how to in set javascript id in input value

i want to inset my javascript id in to the place of input value .
if i give Interest name input value="100"
how can i get tc named table input value="75"
my input form
<tr>
<th>Loan Amount</th>
<th>INTEREST RATE %</th>
<tr>
<tbody>
<td><input disabled type="" name="tc" id="int_amount" class="formcontrol"value=""/></td>
<td><input type="number" name="Interest" id="input2" onkeyup="calculate();"/ class="form-control" value=""/></td>
</tr>
</tbody>
javascript
var vatti = document.pricecal.Interest.value;
var Total = vatti -25;
if(vatti = null)
{
document.getElementById("int_amount").innerHTML = "Rs:"+" "+Total;
}
[want out put like this][1]
Hope this helps you.
function calculate(interest){
var vatti = interest.value;
if (vatti != '') {
var Total = vatti - 25;
document.getElementById("int_amount").value = Total;
}else{
document.getElementById("int_amount").value = '';
}
}
<table>
<tbody>
<tr>
<td><input type="number" name="Interest" id="input2" onkeyup="calculate(this)" onchange="calculate(this)" class="form-control" value=""/></td>
<td><input type="" name="tc" id="int_amount" class="formcontrol" value=""/></td>
</tr>
</tbody>
</table>
Set the .value of the <input> element, not the .innerHTML
document.getElementById("int_amount").value = "Rs:"+" "+Total;
HTML:
<tbody>
<tr>
<td><input type="number" name="Interest" id="input2" class="form-control" value=""/></td>
<td><input type="" name="tc" id="int_amount" class="formcontrol" value=""/></td>
</tr>
</tbody>
Javascript:
document.getElementById('input2').onkeyup = function() {
document.getElementById('int_amount').value = (this.value != '') ? 'Rs: ' + (parseInt(this.value)-25) : '';
}

Auto Table Calculation

I have table with quantity cell when change quantity it need to multiply with other parent td value.and sum the column values .
(i.e) if i change quantity to 2 then the parent rows need multiply by 2 & columns get value get added
I done all the calculation part without input in td now i added input and the calculation got affected i debug and checked it i don't know what would be the problem
Here my fiddle:
https://jsfiddle.net/hahkarthick/57zpk59k/3/
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).val();
console.log(val)
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('val');
$(this).data('val',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1 || val == undefined){
val = 1;
}
$(this).siblings().each(function(){
var tbvalue=$(this).data("val");
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
});
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i <= 4; i++) {
var sum = 0;
var tdBoxes = $('.auto_sum>tbody>tr>td>input:nth-child(' + i + ')');
for(var j=0; j<tdBoxes.length-1;j++)
{
var value = $(tdBoxes[j]).val();
sum += (value == undefined || value == "")? 0 : parseInt(value);
}
// set total in last cell of the column
$('.auto_sum>tbody>tr>td>input:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" data-val="" value="20" name=""></td>
<td><input type="number" data-val="" value="10" name=""></td>
<td><input type="number" data-val="" value="10" name=""></td>
<td><input class="quantity" type="number" name=""></td>
</tr>
<tr>
<td><input type="number" data-val="" value="5" name=""></td>
<td><input type="number" data-val="" value="6" name=""></td>
<td><input type="number" data-val="" value="12" name=""></td>
<td><input class="quantity" type="number" name=""></td>
</tr>
<tr>
<td><input type="number" data-val="" value="45" name=""></td>
<td><input type="number" data-val="" value="23" name=""></td>
<td><input type="number" data-val="" value="22" name=""></td>
<td><input class="quantity" type="number" name=""></td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
Hope this helps...
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover" id="sum_table">
<thead>
<tr class="title">
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" data-val="" value="20[2]" name=""></td>
<td><input type="number" data-val="" value="10" name=""></td>
<td><input type="number" data-val="" value="10" name=""></td>
<td><input class="quantity" type="number" name=""></td>
</tr>
<tr>
<td><input type="number" data-val="" value="5" name=""></td>
<td><input type="number" data-val="" value="6" name=""></td>
<td><input type="number" data-val="" value="12" name=""></td>
<td><input class="quantity" type="number" name=""></td>
</tr>
<tr>
<td><input type="number" data-val="" value="45" name=""></td>
<td><input type="number" data-val="" value="23" name=""></td>
<td><input type="number" data-val="" value="22" name=""></td>
<td><input class="quantity" type="number" name=""></td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<script>
$(document).ready(function(){
$('.quantity').on('change',function(){
var val=$(this).val();
console.log(val)
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('val');
$(this).data('val',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1 || val == undefined){
val = 1;
}
$(this).parent().siblings().each(function(){
var oldval = $(this).find('input').val();
var arr = oldval.split("[");
console.log(arr);
//var newval = val * oldval;
var newval = (val * parseFloat(arr[0])).toFixed(2);
console.log(newval);
if(arr.length > 1) {
newval = newval + "[" + arr[1];
}
$(this).find('input').val(newval);
});
autoSum();
});
autoSum();
});
function autoSum(){
var $dataRows=$("#sum_table tr:not('.total, .title')");
var totals=[0,0,0];
$dataRows.each(function() {
$(this).find('input').each(function(i){
totals[i]+=parseFloat( $(this).val());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
}
</script>
I have updated the fiddle.
I have made following changes :-
$('.quantity').on('change, keyup',function(){ changed to $('.quantity').on('keyup',function(){
$(this).siblings().each(function(){ changed to $(this).parent().siblings().each(function(){
var tbvalue=$(this).data("val"); changed to var tbvalue=$(this).find("input[type=number]").val();
Hope it helps.

Copy table row and increment all name attributes

Let's have a table like this:
<table>
<tr>
<td><input type="text" name="FirstName1" /></td>
<td><input type="text" name="LastName1" /></td>
</tr>
<tr>
<td><input type="text" name="FirstName2" /></td>
<td><input type="text" name="LastName2" /></td>
</tr>
</table>
I want to have a button that will add new row at the end of the table with incremented name attributes so it will look like this:
<table>
<tr>
<td><input type="text" name="FirstName1" /></td>
<td><input type="text" name="LastName1" /></td>
</tr>
<tr>
<td><input type="text" name="FirstName2" /></td>
<td><input type="text" name="LastName2" /></td>
</tr>
<tr>
<td><input type="text" name="FirstName3" /></td>
<td><input type="text" name="LastName3" /></td>
</tr>
</table>
And so on.
So far I have this but it does not increment name attributes:
$("#newRowButton").click(function(){
$("table tr:last").clone().appendTo("table");
});
$("#newRowButton").click(function() {
$("table tr:last")
.clone()
.appendTo("table")
.find(':input')
.attr('name', function(index, name) {
return name.replace(/(\d+)$/, function(fullMatch, n) {
return Number(n) + 1;
});
})
});
Live demo.
$("#newRowButton").click(function(){
var trows = $("table tr:last").clone();
trows.find('td input').attr("name",function(i,a){
var p = new RegExp("((?:[a-z][a-z]+))(\\d+)",["i"]);
var m = p.exec(a);
var index = parseInt(m[1]);
index++;
return m[0]+index;
});
trows.appendTo("table");
});
var clonedRow = $("#EventType tr:last").clone();
$("input", clonedRow).attr('name', 'FirstName3'); // reset the name
you can get the name attribute and increment by 1
Reference

Categories