jQuery select input within a td for all rows - javascript

I am trying to calculate the values with all the input fields within a table upon change.
Here is the sample HTML table targeted and also the jQuery code I am trying to use to get the values from all input fields in the table by iterating over the rows using foreach:
$('#mytable :input').change(function() {
var numrows = 1;
var rows;
$('#out').text('');
$('#mytable tr').each(function() {
var date = $(this).children('td:eq(1)');
var obj = $(this).children('td:eq(2):input').value;
var comma = $('#queryTable tbody tr').length != numrows ? "," : "]";
var row = "{\"" + date + "\";\"" + obj + "\"}" + comma + "\n";
//row += date * obj;
//row = numrows == 1 ? "["+row : row;
$('#out').append(row);
numrows++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out">
Test
</div>
<table id="mytable" border="1">
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
<tr>
<td>value1</td>
<td>1</td>
<td>Label1:
<Input type="text"></Input>
</td>
</tr>
<tr>
<td>value2</td>
<td>3</td>
<td>Label2:
<Input type="text"></Input>
</td>
</tr>
<tr>
<td>value3</td>
<td>ttt</td>
<td>Label3:
<Input type="text"></Input>
</td>
</tr>
</table>
Fiddle sample code

i recomend you to use keyup instead of change because the change will not trigger till the input lost focus:
$('#mytable :input').keyup(function(){
var numrows = 1;
var rows;
$('#out').text('');
$('#mytable tr:not(:first-child)').each(function(){
var date = $(this).children().eq(1).text();
var obj = $(this).children().eq(2).children('input').val();
var comma = $('#queryTable tbody tr').length != numrows ? "," : "]";
var row = "{\""+date+"\";\""+obj+"\"}"+comma+"\n";
//row += date * obj;
//row = numrows == 1 ? "["+row : row;
$('#out').append(row);
numrows++;
});
});
here is your working jsfiddle
http://jsfiddle.net/ZZYD4/891/
btw i ignore the first row adding this to the selector :not(:first-child) because that is the header row

Related

jQuery sum the values of table rows

hello i have this table
i want to get the total of each row in the total column
jQuery
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var leads = $('#leads');
var budget_total_year = $('#full_year_cost');
var budget_total_month = $('#share_cost');
var budget_per_lead = $('#cost_per_lead');
leads.append('<th>' + value.olxTotal + '</th>');
budget_total_year.append('<th>' + value.budget_total_year + '</th>');
budget_total_month.append('<th>' + value.budget_total_month + '</th>');
budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
})
})
HTML
<tbody id="tableData-marketMonth">
<tr id="leads">
<th>Leads</th>
</tr>
<tr id="full_year_cost">
<th>Full Year Cost</th>
</tr>
<tr id="share_cost">
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr id="cost_per_lead">
<th>Cost per Lead</th>
</tr>
</tbody>
i was going to calculate the total through php but i though it can be easier
using jQuery just putting the sum of each row at the end
Thank you very much
Create variables before the loop. add to the variables in the loop and then assign the sum at the end.
$.get('/dashboard/costs', function(data){
var sumLeads = 0;
var sumFullYearCost = 0;
var sumShareCost = 0;
var sumCostPerLead = 0;
var tr_leads = $('#leads');
var tr_budget_total_year = $('#full_year_cost');
var tr_budget_total_month = $('#share_cost');
var tr_budget_per_lead = $('#cost_per_lead');
$.each(data,function(i,value){
tr_leads.append('<th>' + value.olxTotal + '</th>');
tr_budget_total_year.append('<th>' + value.budget_total_year + '</th>');
tr_budget_total_month.append('<th>' + value.budget_total_month + '</th>');
tr_budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
sumLeads += value.olxTotal;
sumFullYearCost += value.budget_total_year;
sumShareCost += value.budget_total_month;
sumCostPerLead += value.budget_per_lead;
});
tr_leads.append('<th>' + sumLeads + '</th>');
tr_budget_total_year.append('<th>' + sumFullYearCost + '</th>');
tr_budget_total_month.append('<th>' + sumShareCost + '</th>');
tr_budget_per_lead.append('<th>' + sumCostPerLead + '</th>');
});
Example for leads row using Array.map and Array.reduce. Use jQuery to get the td elements.
var leads = $('#leads');
const total = leads.children('td').toArray().map(x=>Number(x.innerHTML)).reduce((sum, x) => sum + x)
leads.append(`<th>${total}</th>`);
Try something like this.
$('#tableData-marketMonth tr').each(function () {
var row = $(this);
var rowTotal = 0;
$(this).find('th').each(function () {
var th = $(this);
if ($.isNumeric(th.text())) {
rowTotal += parseFloat(th.text());
}
});
row.find('th:last').text(rowTotal);
});
NOTE: change 'th' to 'td' if you have td's. Looking at your jquery, it looks like you are appending th's.
You can use my written code to vote if you like it...
HTML
<table>
<thead>
<tr>
<th>MAX ATK</th>
<th>MAX DEF</th>
<th>MAX HP</th>
<th>Overall</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat">8170</td>
<td class="combat">6504</td>
<td class="combat">6050</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">8500</td>
<td class="combat">10200</td>
<td class="combat">7650</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">9185</td>
<td class="combat">7515</td>
<td class="combat">9185</td>
<td class="total-combat"></td>
</tr>
</tbody>
</table>
jquery
$(document).ready(function () {
//iterate through each row in the table
$('tr').each(function () {
//the value of sum needs to be reset for each row, so it has to be set inside the row loop
var sum = 0
//find the combat elements in the current row and sum it
$(this).find('.combat').each(function () {
var combat = $(this).text();
if (!isNaN(combat) && combat.length !== 0) {
sum += parseFloat(combat);
}
});
//set the value of currents rows sum to the total-combat element in the current row
$('.total-combat', this).html(sum);
});
});

How to show total of dynamically added column using jquery

I have made a shopping cart where I added row based on autocomplete search. and based on quantity price changed. But I want to find the total of subtotal..I have written the update part. But it's showing 0 instead of actual value. Can anyone help me to find it out what's the wrong in my jQuery code..Thank You!
$('#searchName').autocomplete({
source: '{!! asset('nameAutocomplete') !!}',
select:function(suggestion,ui){
event.preventDefault();
var $tbody = $('#example tbody');
$tbody.append('<tr><td class="id">' + ui.item.id +
'</td><td class="name">' + ui.item.value +
'</td><td class="price">' + ui.item.price +
'</td><td><input type="text" class="quantity" value="1"/></td><td><input type="text" class="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');
$('.quantity').on('keyup',function(){
var tot = $(this).parent().prev().html() * this.value;
$(this).parent().next().find('.total').val(tot);
console.log(calculateSum());
});
function calculateSum(){
var sum = 0;
$(".total").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
return sum;
}
}
});
Here is table part :
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
$(".total") is an input, so you should use var value = $(this).val();, not var value = $(this).text();

Unable to retieve the particular value of cell on table using javascript

I am using the following code to retrieve the values of a particular cell of a table.:
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].document.getElementsByTagName("input").item(1).value;
var lifecycycleattr1 = r.cells[0].document.getElementsByTagName("input").item(2).value;
var stateattr1 = r.cells[0].document.getElementsByTagName("input").item(3).value;
}
}
}
and my html code is :
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
I want to retrieve each value of a particular.
Its just an example.I have more thane two rows for which i need for loop to get the values of each cell.
See if this points you in the right direction:
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].innerText;
var lifecycycleattr1 = r.cells[1].innerText;
var stateattr1 = r.cells[2].innerText;
alert('catname1: ' + catname1 + '\r\n' +
'lifecycycleattr1: ' + lifecycycleattr1 + '\r\n' +
'stateattr1: ' + stateattr1 + '\r\n');
}
}
}
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
<input type="button" onclick="addCatAttr()" value="Click me" />
This can help better...
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].innerHTML;
var lifecycycleattr1 = r.cells[1].innerHTML;
var stateattr1 = r.cells[2].innerHTML;
alert('catname1: ' + catname1 + '\r\n' +
'lifecycycleattr1: ' + lifecycycleattr1 + '\r\n' +
'stateattr1: ' + stateattr1 + '\r\n');
}
}
}
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
<input type="button" onclick="addCatAttr()" value="Click me" />
You need to apply two for loops one for table length and the other for the each td in tr. This is the code.
var table = document.getElementById('tblAttributes1'),
rows = table.getElementsByTagName('tr');
for (var i = 0; i< rows.length; i++) {
var tds = rows[i].getElementsByTagName('td');
for(var x=0;x<tds.length;x++){
console.log(tds[x].innerHTML);
}
And the fiddle is-
http://jsfiddle.net/09q6n3m2/16/

javascript: add and remove table row, cant get correct numbering

i have table like this:
<button type="button" onclick="addRow();">Add Row</button>
<table id="item_table" cellspacing="1" cellpadding="1" border=1>
<tr>
<td>No.</td>
<td>text</td>
<td>Action</td>
</tr>
<tr id="theFirstRow">
<td class="itemNumber">1</td>
<td>text</td>
<td><button type="button" onclick="deleteRow(this)">Delete</button> </td>
</tr>
</table>
and JS code like this:
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('item_table').deleteRow(i);
}
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("theFirstRow").cloneNode(true);
var tbs = null;
var lastRow = 0;
var currentRow = 0;
var numbering = 0;
tbs = document.getElementsByClassName("itemNumber");
lastRow = tbs.length - 1;
currentRow = tbs.length;
console.log("lastRow : " + lastRow);
numbering = parseInt(currentRow, 10) + 1;
console.log("numbering : " + numbering);
x.innerHTML = x.innerHTML.replace('<td class="itemNumber">' + currentRow + '</td>', '<td class="itemNumber">' + numbering + '</td>');
return x;
}
function addRow() {
var t = document.getElementById("item_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
Updated: JSFIDDLE HERE
I cant get the increment numbering and delete row numbering correctly, when i check from console log, the number seem correct. Any help would be great.
I think I would go about this a little bit differently. Here is how I would do it. Maybe it isn't what you were looking for. JSFiddle.
HTML (Take out onclicks, add some ids and classes)
<button id="add" type="button">Add Row</button>
<table id="item_table" cellspacing="1" cellpadding="1" border=1>
<tr>
<td>No.</td>
<td>text</td>
<td>Action</td>
</tr>
<tr id="template">
<td class="itemNumber">1</td>
<td>text</td>
<td><button class="delete" type="button">Delete</button> </td>
</tr>
</table>
JS
(function() {
var template = document.getElementById("template"),
table = document.getElementById("item_table"),
display = template.style.display;
document.getElementById("add").addEventListener("click", function() {
var row = template.cloneNode(true);
row.style.display = display;
row.querySelector(".delete").addEventListener("click", function() {
table.removeChild(this);
}.bind(row));
row.querySelector(".itemNumber").innerHTML = table.children.length - 1;
table.appendChild(row);
});
template.style.display = "none";
}());

How to get the index of a particular element

I got the following code from the designer:
<table class="items">
<thead>
<tr>
<th id="name">name</th>
<th id="category">category</th>
<th id="zip">zip</th>
<th id="city">city</th>
<th id="street">street</th>
<th id="latitude">latitude</th>
<th id="longitude">longitude</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MyCompany</td>
<td>Company</td>
<td>18360</td>
<td>Stroudsburg</td>
<td>4 Scott Str.</td>
<td>40.9891</td>
<td>-75.1962</td>
</tr>
</tbody>
</table>
Using jQuery, how can I get the longitude and latitude values by taking into account the th elements with the specified id? The order of the columns might change later so direct indexing is not an option. However the id values will remain the same.
var latIndex = document.getElementById('latitude').cellIndex;
var longIndex = document.getElementById('longitude').cellIndex;
var row = document.querySelector(".items .odd");
var latitude = row.cells[latIndex];
var longiture = row.cells[longIndex];
latitude = latitude.textContent || latitude.innerText;
longitude = longitude.textContent || longitude.innerText;
Using ONLY raw JavaScript, guaranteed to be at least 8 times faster than jQuery (20 on more complex pages) ;)
You can use the .index() method to get the location of the latitude and longitude headers and then get that same location in the body.
// get column number for lat and long
var latIndex = $("#latitude").index();
var longIndex = $("#longitude").index();
// get rows that contain the actual data
var rows = $(".items .odd td");
// get the desired data from the same columns as titles
var latitude = rows.eq(latIndex).text();
var longitude = rows.eq(longIndex).text();
Demo here: http://jsfiddle.net/jfriend00/bCXbw/
You can use the .index() method:
var latIndex = $("#latitude").index(),
longIndex = $("#longitude").index();
// do something with the values from each row
$("tbody tr").each(function() {
var $tds = $(this).find("td"),
latValue = $tds.eq(latIndex).text(),
longValue = $tds.eq(longIndex).text();
console.log(latValue + ", " + longValue);
});​
Demo: http://jsfiddle.net/mjaVp/
Another way using index() with :nth-child()
var lat = jQuery("#latitude");
var lng = jQuery("#longitude");
var latInd = jQuery("table thead th").index( lat ) + 1;
var lngInd = jQuery("table thead th").index( lng ) + 1;
var lats = jQuery("table tbody tr td:nth-child(" + latInd + ")");
var lngs = jQuery("table tbody tr td:nth-child(" + lngInd + ")");
console.log(lats);
console.log(lngs);
fiddle
var lat = $('#latitude').index();
var long = $('#longitude').index();
console.log($('tr.odd td:eq('+lat+')').html()); //outputs 40.9891
console.log($('tr.odd td:eq('+long+')').html()) // outputs -75.1962
This assumes that the ordering of element is consistent, which looking at your code it should be.

Categories

Resources