Find element based on highest value of inputbox in same table row - javascript

I have a table with three columns.
Column 1 has inputboxes.
Column 2 contains a "conversion" number which multiplies it's value with the value in the inputbox (column 1)
and the result is outputted in column 3.
It would look something like this:
5 2 10
1 1 1
2 1 2
3 2 6
How can I get column 3's value based on the highest inputbox value in the same row?
My code so far:
HTML
<table border="1px">
<tbody id="mbtbody">
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">5</td>
<td class="totals"></td>
</tr>
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">1</td>
<td class="totals"></td></tr>
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">1</td>
<td class="totals"></td>
</tr>
</tbody>
</table>
jQuery
$("#btn").click(function(){
var rows = $("#mbtbody").children("tr");
var total = 0;
rows.each(function(idx, row) {
var $row = $(row);
total += parseInt($row.find('input.weightinputclass').val());
$("#totalweight").html(total);
});
})
$(document).on('input', '.weightinputclass', function () {
var $row = $(this).closest("tr");
var weight = $row.find("input.weightinputclass").val();
var conversion= $row.find(".conversionclass").html();
$row.find(".totals").text(weight*conversion);
})
Fiddle: https://jsfiddle.net/rdawkins/9fyLqfgr/16/

Here is a solution I found:
Javascript
$("#btn").click(function(){
var rows = $("#mbtbody").children("tr");
var total = 0;
rows.each(function(idx, row) {
var $row = $(row);
total += parseInt($row.find('input.weightinputclass').val());
$("#totalweight").html(total);
});
var currentMax = 0;
var currentMaxEl;
$('.weightinputclass').each(function (idx, element) {
var elVal = parseInt($(element).val());
if(elVal > currentMax) {
currentMax = elVal;
currentMaxEl = $(element);
}
});
var maxWeight = currentMaxEl.parent().parent().children('.totals').first().html();
$('#highestinput').html(2000 - maxWeight);
})
$(document).on('input', '.weightinputclass', function () {
var $row = $(this).closest("tr");
var weight = $row.find("input.weightinputclass").val();
var conversion= $row.find(".conversionclass").html();
$row.find(".totals").text(weight*conversion);
});
Fiddle
https://jsfiddle.net/9v6j8qub/2/

Related

get the sum of 2nd column in html table

input : <table> <tr> <td>100</td> </tr> <tr> <td>200</td> </tr> </table> from the input it should return me the sum=300 instead I'm getting the output as 100200
function Save_Name()
{
var Invoice = $("#text_invoice").val();
var Name = $("#text_name").val();
var Date = $("#text_date").val();
var Amount = 0;
var n = $("table").find("tr").length;
if (n - 1 > 0)
{
for (var i = 0 ; i < n; i++)
{
var Amt = $("#table1").find("tr").eq(i).find("td").eq(2).text();
Amount += parseFloat(Amt);
}
}
}
eq starts with 0 index.The output 100200 is because it is concatenating the string instead of adding the values.Also use parseInt to convert the number from string to integer.
function Save_Name() {
var Amount = 0;
// will get all tr
var n = $("#table1 tr");
n.each(function(i, v) {
// table have only one td per tr so eq(0) will give first td
// trim is used to remove any white space
Amount += parseInt($(v).eq(0).text().trim(), 10)
})
console.log(Amount)
}
Save_Name()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1">
<tr>
<td>100</td>
</tr>
<tr>
<td>200</td>
</tr>
</table>
Here's another way to do the same thing. Basically, I use map to create a map of integer values, then I use "get" to convert them into an array, and finally I use reduce to calculate the sum of the values in the array.
P.S.: To calculate the second column, all you need to do is to use nth-child(2) instead of nth-child(1).
$(function(){
var sum = $('#table1 tr td:nth-child(1)').map(function() {
return parseInt($(this).html(), 10)
}).get().reduce(function(a, v){
return a + v;
}, 0);
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="table1">
<tr>
<td>100</td>
</tr>
<tr>
<td>200</td>
</tr>
</table>
I have alert the value of sum Amount and it is equal to 300 .
You were doing some mistake as eq(2) instead of eq(0)
But Here's the working snippet:
function Save_Name()
{
var Amount = 0;
var n = $('#test tr').length;
// alert(n);
if (n - 1 > 0)
{
for (var i = 0 ; i < n; i++)
{
var Amt = $("#test").find("tr").eq(i).find("td").eq(0).text();
Amount += parseFloat(Amt);
}
alert(Amount);
}
}
Save_Name();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='test'>
<tr> <td>100 </td></tr>
<tr> <td>200 </td></tr>
</table>

Add two array values of same name using script

I need to multiply two values of a and b and display in c. Also I need to display the addition value of c using script. Please check my code below:
HTML:
<table border="1" id="table" class="table">
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
<?php
$select= "SELECT * from table where id=1";
$result = mysql_query($select);
$row_count=1;
while($row = mysql_fetch_assoc($result))
{
?>
<tr>
<td><input type="text" value="<?php echo $row['name_a']; ?>" name="name_a[]" class="name_a"></td>
<td><input type="text" value="<?php echo $row['code_a']; ?>" name="code_a[]" class="code_a"></td>
<td><input type="text" name="id_a[]" class="id_a" ></td>
</tr>
<?php
$row_count++;
}
?>
</table>
<input type="text" name="total" class="total">
SCRIPT:
$(document).ready(function() {
$('#table').on('keyup', '.name_a', cal)
.on('keyup', '.code_a', cal)
.on('keyup', '.id_a', cal);
function cal() {
var $row = $(this).closest('tr'),
name_a = $row.find('.name_a').val(),
code_a = $row.find('.code_a').val(),
id_a = $row.find('.id_a').val(),
id_a_calc = name_a * code_a;
$row.find('.id_a').val(id_a_calc)
}
});
OUTPUT
a b c
1 2 2
2 4 8
By the above script,I can multiply a and b and display in c.But how to add two values of 'c' and display in total text box.Need help
try this:
$(document).ready(function() {
$('#table').on('keyup', '.name_a', cal)
.on('keyup', '.code_a', cal)
.on('keyup', '.id_a', cal);
});
function cal() {
var $row = $(this).closest('tr'),
name_a = $row.find('.name_a').val(),
code_a = $row.find('.code_a').val(),
id_a = $row.find('.id_a').val(),
id_a_calc = name_a * code_a;
$row.find('.id_a').val(id_a_calc);
var total = 0;
$(".id_a").each(function() {
// console.log($(this).val());
if($(this).val().length > 0){
total += parseInt($(this).val(), 10);
}
});
$(".total").val(total);
}
Put this in cal after you update $row.find('.id_a').val()
var total = 0;
$(".id_a").each(function() {
total += parseInt($(this).val(), 10);
});
$(".total").text(total);
try this code:-
$(document).ready(function() {
$("#btn").click(function() {
var cValue = 0;
$('#table tr td:nth-child(3)').each(function() {
cValue += parseInt($(this).html());
});
$("#total").val(cValue)
});
});
jsfiddle example:-
http://jsfiddle.net/c2S5d/21/

Sum column totals depending on text of another column using jQuery

I have this code that I use to calculate totals in specific columns based on the text in a different column. It works just fine, but I'm learning, so I would like to know if there is way to consolidate this code. As you can see I run a "each()" twice, once for each column. The first each check for "A" in the first column, then goes to the second column and adds the rows that meet the criteria. Similar on the second column, just that it looks for "B" and add columns 3. Is there a way to run the each function only once and check both column at the same time?
JS:
//Second Column
var total = 0;
$("#theTable tr:contains('A') td:nth-of-type(2)").each(function () {
var pending = parseInt($(this).text());
total += pending;
});
$("#theTable tfoot tr:last-of-type td:nth-of-type(2)").text(total);
//Third Column
var total2 = 0;
$("#theTable tr:contains('B') td:nth-of-type(3)").each(function () {
var pending2 = parseInt($(this).text());
total2 += pending2;
});
$("#theTable tfoot tr:last-of-type td:nth-of-type(3)").text(total2);
HTML:
<table id="theTable">
<thead>
<tr>
<th>MONTH</th>
<th>PENDING</th>
<th>DENIED</th>
</tr>
</thead>
<tbody></tbody>
<tr>
<td>A</td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>B</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>3</td>
<td>2</td>
</tr>
<tr>
<td>C</td>
<td>3</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>B</td>
<td>4</td>
<td>2</td>
</tr>
<tfoot>
<tr>
<td>TOTALS:</td>
<td></td>
<td></td>
</tr>
</tfoot>
This may look simple for some of you, but again, I'm just learning some JS now.
Thanks!
You could try something like this:
var total = {A:{row:1,t:0},B:{row:2,t:0}};
$('#theTable tr').each(function() {
$row = $(this);
$.each(total, function(key, col) {
rowFil = $row.filter(':contains("' + key + '")');
col.t += (rowFil) ? +rowFil.find('td:eq(' + col.row + ')').text() : 0;
});
});
$("#theTable tfoot tr:last td:eq(1)").text(total.A.t);
$("#theTable tfoot tr:last td:eq(2)").text(total.B.t);
someThing of this sort might Help ...
var trs = $('#'+tblID).find('tr');
var total1 = 0;
var total2 = 0;
$.each(trs, function(k, v) {
if ($(v).text == "A"){
total1 += parseInt($(v).parent('tr').find('td:eq(2)').text());
}
if ($(v).text == "B"){
total2 += parseInt($(v).parent('tr').find('td:eq(3)').text())
}
});
Here is another approach - I've summed up all statistics for all possible values:
var totals = [];
$('#theTable tbody tr').each(function(e) {
var tds= $(this).find('td');
var index = $(tds[0]).text();
var pending = parseInt($(tds[1]).text(), 10);
var denied = parseInt($(tds[2]).text(), 10);
if (totals[index] == undefined)
totals[index] = { Pending: 0, Denied: 0 };
totals[index].Pending += pending;
totals[index].Denied += denied;
});
for (var key in totals)
$('#theTable tfoot').append('<tr><td>'+key+'</td><td>'+
totals[key].Pending+'</td><td>'+totals[key].Denied+'</td></tr>');
I've also updated markup a little, here is jsfiddle. The code may be not so pretty, but doing more stuff and can be refactored.
Creating a second table with the sums makes it easier to analyse the data.
SOLUTION
JS
//make a list of unique months
var months = [];
$('#theTable tr td:nth-of-type(1)').each(function(){
var month = $(this).text();
if(months.indexOf(month) < 0) months.push(month);
});
console.log('months', months);
//make a data structure with sums
var data = {};
var tr = $('#theTable tr');
$.each(months, function(){
var month = this;
data[month] = {
pending: 0,
denied: 0
};
tr.each(function(){
var ch = $(this).children();
var m = $(ch[0]).text();
var pending = $(ch[1]).text();
var denied = $(ch[2]).text();
if(m == month) {
data[month].pending += parseInt(pending);
data[month].denied += parseInt(denied);
}
});
});
console.log('data', data);
//make a table with the data
var table = $('<table>');
table.append($('<tr>'+
'<th>MONTH</th>'+
'<th>PENDING</th>'+
'<th>DENIED</th>'+
'</tr>'));
$.each(data, function(month){
table.append($('<tr>'+
'<td>'+month+'</td>'+
'<td>'+data[month].pending+'</td>'+
'<td>'+data[month].denied+'</td>'+
'</tr>'));
});
$('body').append(table);

How to check for duplicate row using javascript

how do I check for duplicate row in a table using javascript? The following is part of my code:
<table id="t1">
<tr>
<td>Text A</td>
<td>Text B</td>
<td>Cbx A</td>
</tr>
<% int count1 = -1;
for(int i=0; i<3; i++) { %>
<tr>
<td><input type="text" id="textA<%=i%>"></td>
<td><input type="text" id="textB<%=i%>"></td>
<td><select name="cbx_A<%=i%>">
<option value="A">Option1</option>
<option value="B">Option2</option>
</select>
</td
</tr>
<%count1 =i;
}%>
<tr>
<td><input type="button" onclick="check(<%=count1%>)" value="Check"></td>
</tr>
</table>
So based on this code, I will have 3 rows of text A,textB and cbxA. With that, how do I check whether user input the same values for 2 of the rows or all three rows?
I tried using servlet but theres too much work involve. So yeah is there a way to do this using java script instead?
Thanks in advance for any possible help.
Using this code it will check for duplication in one table column
then take all rows of table that are duplicated and put their ids in array
so you will get an array of rows id
but ur table has to have an id for each row
var columnNumber = 1;
var table = document.getElementById('t1');
var rowLength = table.rows.length;
var arrReocrds = new Array();
var arrCount = 0;
var listCount = 0;
var arr = new Array();
$('#t1 td:nth-child(' + colNumber + ')').each(function () {
var recordValue = $(this).html().trim();
var flagFirstTime = true;
//loop through table to check redundant of current record value
for (var i = 1; i < rowLength; i += 1) {
{
var row = table.rows[i];
var recordId = //put here row.id or anything that you can put it in the list
var cell = row.cells[colNumber - 1];
var value = cell.innerText.trim();
if (value == recordValue) {
if (!arr.contains(value)) {
if (flagFirstTime != true) {
arrReocrds[arrCount] = recordId;
arrCount++;
}
else
flagFirstTime = false;
}
else
break;
}
}
}
//create list for items in column
//to be sure that the item that has been taken and checked never be checked again by their other redundant records
arr[listCount] = recordValue;
listCount++;
});

How to iterate a table rows with JQuery and access some cell values?

<table class="checkout itemsOverview">
<tr class="item">
<td>GR-10 Senderos</td>
<td><span class="value">15.00</span> €</td>
<td><input type="text" value="1" maxlength="2" class="quantity" /></td>
</tr>
<tr class="item">
<td>GR-10 Senderos<br/>GR-66 Camino de la Hermandad<br/>GR 88 Senderos del Jarama<br/>Camino del Cid</td>
<td><span class="value">45.00</span> €</td>
<td><input type="text" class="quantity" value="1" maxlength="2"/></td>
</tr>
</table>
I was trying with the next code to get the value and quantity of each item.
$("tr.item").each(function(i, tr) {
var value = $(tr + " span.value").html();
var quantity = $(tr + " input.quantity").val();
});
It is not working. Can anyone help me?
$("tr.item").each(function() {
$this = $(this);
var value = $this.find("span.value").html();
var quantity = $this.find("input.quantity").val();
});
do this:
$("tr.item").each(function(i, tr) {
var value = $("span.value", tr).text();
var quantity = $("input.quantity", tr).val();
});
try this
var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');
function iterate(selector)
{
var result = '';
if ($(selector))
{
$(selector).each(function ()
{
if (result == '')
{
result = $(this).html();
}
else
{
result = result + "," + $(this).html();
}
});
}
}

Categories

Resources