How to access all the row data when sending this - javascript

Let's say I have something like this:
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>Options</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td>McDonalds</td>
<td><img src="delete.png"/></td>
</tr>
</table>
function delete(this)
{
//how to access all the data from this row (id,name,lastname)
}

I would recommend to separate HTML from Jquery or javascript and work with events:
Add a selector in your HTML like delete:
<td><img src="delete.png"/></td>
And then just select the row and the columns you want to work with using eq function.
$('.delete').click(function(e){
e.preventDefault(); //disallowing the link
var row = $(this).closest('tr');
var td = row.find('td');
var id = td.eq(0).text(); //first column
var lastName = td.eq(1).text(); //second column
var options = td.eq(2).text(); //third column
alert("id: " + id +"\n" + "lastName: " + lastName + "\n" + "Options: " + options);
});
http://jsfiddle.net/7c4E3/
Alternatively you can make use of this answer to create an array of data if you wish.

Is it possible to add classes on those columns? If it is, try this:
HTML:
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>Options</th>
</tr>
<tr>
<td class="id">1</td>
<td class="name">John</td>
<td class="lastname">McDonalds</td>
<td><a class="deleteRow" href="#" onclick=""><img src="delete.png"/></a>
</td>
</tr>
</table>
jQuery:
$(".deleteRow").click(function (e) {
var thisrow = $(this).closest("tr");
var id = thisrow.find(".id").text();
var name = thisrow.find(".name").text();
var lastname = thisrow.find(".lastname").text();
alert("You selected " + id + ": " + name + " " + lastname);
});
Here's a FIDDLE

Then i suggest you to try with jQuery way:
Here .del is the class name of the delete button and you can find that by .eq() function which selects elements by their indexes.
$('.del').on('click', function(){
var theRow = $(this).closest('tr').find('td');
var id = theRow.eq(0).text();
var fName = theRow.eq(1).text();
var lName = theRow.eq(2).text();
console.log(id + ' ' + fName + ' '+ lName);
});

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

jQuery select input within a td for all rows

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

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

How can I append <td> dynamically according to the number of values in json

I am creating a program where I get value from json and I want to show that value in a table. I am getting all the values in console but only the last arrays value is displayed in the table. So I want to append the dynamically so that it will create new td according to the values in json file.
HTML Code:
<tr>
<td>Count:</td>
<td id="count"></td>
</tr>
<tr>
<td>Created:</td>
<td id="created"></td>
</tr>
<tr>
<td>Lang:</td>
<td id="lang"></td>
</tr>
<tr>
<td>ID:</td>
<td id="id"></td>
</tr>
<tr>
<td>Name:</td>
<td id="Name"></td>
</tr>
<tr>
<td>Rate:</td>
<td id="Rate"></td>
</tr>
<tr>
<td>Date:</td>
<td id="Date"></td>
</tr>
<tr>
<td>Time:</td>
<td id="Time"></td>
</tr>
<tr>
<td>Ask:</td>
<td id="Ask"></td>
</tr>
<tr>
<td>Bid:</td>
<td id="Bid"></td>
</tr>
In this file I have only one value for count, created and lang. Whereas I have 29 values for the rest of the fields.
Javascript file:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDARS%22,%20%22USDAUD%22,%20%22USDBHD%22,%20%22USDBRL%22,%20%22USDGBP%22,%20%22USDCNY%22,%20%22USDHRK%22,%20%22USDDKK%22,%20%22USDEGP%22,%20%22USDSVC%22,%20%22USDEEK%22,%20%22USDETB%22,%20%22USDEUR%22,%20%22USDHKD%22,%20%22USDHUF%22,%20%22USDINR%22,%20%22USDIDR%22,%20%22USDJPY%22,%20%22USDKWD%22,%20%22USDNZD%22,%20%22USDNOK%22,%20%22USDPKR%22,%20%22USDPHP%22,%20%22USDPLN%22,%20%22USDRUB%22,%20%22USDSGD%22,%20%22USDZAR%22,%20%22USDSEK%22,%20%22USDCHF%22%29&format=json&env=store://datatables.org/alltableswithkeys', function (json) {
// Set the variables from the query array
//alert(json.query.results.rate.length);
var count = json.query.count;
console.log('Count : ', count);
var created = json.query.created;
console.log('Created : ', created);
var lang = json.query.lang;
console.log('Lang : ', lang);
for(i=0; i<json.query.results.rate.length; i++)
{
var id = json.query.results.rate[i].id;
console.log('ID : ', id);
var name = json.query.results.rate[i].Name;
console.log('Name : ', name);
var rate = json.query.results.rate[i].Rate;
console.log('Rate : ', rate);
var date = json.query.results.rate[i].Date;
console.log('Date : ', date);
var time = json.query.results.rate[i].Time;
console.log('Time : ', time);
var ask = json.query.results.rate[i].Ask;
console.log('Ask : ', ask);
var bid = json.query.results.rate[i].Bid;
console.log('Bid : ', bid);
//}
// Set the table td text
$('#count').text(count);
$('#created').text(created);
$('#lang').text(lang);
$('#id').text(id);
$('#Name').text(name);
$('#Rate').text(rate);
$('#Date').text(date);
$('#Time').text(time);
$('#Ask').text(ask);
$('#Bid').text(bid);
}
});
JSON data (source):
{"query":{"count":29,"created":"2015-07-07T07:33:27Z","lang":"nl-NL","results":{"rate":[{"id":"USDARS","Name":"USD/ARS","Rate":"9.1173","Date":"7/7/2015","Time":"8:33am","Ask":"9.1214","Bid":"9.1173"},{"id":"USDAUD","Name":"USD/AUD","Rate":"1.3374","Date":"7/7/2015","Time":"8:33am","Ask":"1.3376","Bid":"1.3374"},{"id":"USDBHD","Name":"USD/BHD","Rate":"0.3770","Date":"7/7/2015","Time":"8:33am","Ask":"0.3790","Bid":"0.3770"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.1391","Date":"7/7/2015","Time":"8:33am","Ask":"3.1392","Bid":"3.1391"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6428","Date":"7/7/2015","Time":"8:33am","Ask":"0.6428","Bid":"0.6428"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.2098","Date":"7/7/2015","Time":"8:33am","Ask":"6.2104","Bid":"6.2098"},{"id":"USDHRK","Name":"USD/HRK","Rate":"6.8687","Date":"7/7/2015","Time":"8:33am","Ask":"6.8988","Bid":"6.8687"},{"id":"USDDKK","Name":"USD/DKK","Rate":"6.7676","Date":"7/7/2015","Time":"8:33am","Ask":"6.7701","Bid":"6.7676"},{"id":"USDEGP","Name":"USD/EGP","Rate":"7.7327","Date":"7/7/2015","Time":"8:33am","Ask":"7.7352","Bid":"7.7327"},{"id":"USDSVC","Name":"USD/SVC","Rate":"8.7395","Date":"7/7/2015","Time":"8:33am","Ask":"8.7445","Bid":"8.7395"},{"id":"USDEEK","Name":"N/A","Rate":"N/A","Date":"N/A","Time":"N/A","Ask":"N/A","Bid":"N/A"},{"id":"USDETB","Name":"USD/ETB","Rate":"20.6850","Date":"7/7/2015","Time":"8:33am","Ask":"20.7880","Bid":"20.6850"},{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9070","Date":"7/7/2015","Time":"8:33am","Ask":"0.9070","Bid":"0.9070"},{"id":"USDHKD","Name":"USD/HKD","Rate":"7.7551","Date":"7/7/2015","Time":"8:33am","Ask":"7.7552","Bid":"7.7551"},{"id":"USDHUF","Name":"USD/HUF","Rate":"286.5400","Date":"7/7/2015","Time":"8:33am","Ask":"286.8600","Bid":"286.5400"},{"id":"USDINR","Name":"USD/INR","Rate":"63.3839","Date":"7/7/2015","Time":"8:33am","Ask":"63.3990","Bid":"63.3839"},{"id":"USDIDR","Name":"USD/IDR","Rate":"13298.0000","Date":"7/7/2015","Time":"8:33am","Ask":"13310.0000","Bid":"13298.0000"},{"id":"USDJPY","Name":"USD/JPY","Rate":"122.6850","Date":"7/7/2015","Time":"8:33am","Ask":"122.7000","Bid":"122.6850"},{"id":"USDKWD","Name":"USD/KWD","Rate":"0.3027","Date":"7/7/2015","Time":"8:33am","Ask":"0.3032","Bid":"0.3027"},{"id":"USDNZD","Name":"USD/NZD","Rate":"1.5032","Date":"7/7/2015","Time":"8:33am","Ask":"1.5035","Bid":"1.5032"},{"id":"USDNOK","Name":"USD/NOK","Rate":"8.1378","Date":"7/7/2015","Time":"8:33am","Ask":"8.1403","Bid":"8.1378"},{"id":"USDPKR","Name":"USD/PKR","Rate":"101.7300","Date":"7/7/2015","Time":"8:33am","Ask":"101.7600","Bid":"101.7300"},{"id":"USDPHP","Name":"USD/PHP","Rate":"45.1575","Date":"7/7/2015","Time":"8:33am","Ask":"45.1680","Bid":"45.1575"},{"id":"USDPLN","Name":"USD/PLN","Rate":"3.8149","Date":"7/7/2015","Time":"8:33am","Ask":"3.8180","Bid":"3.8149"},{"id":"USDRUB","Name":"USD/RUB","Rate":"57.3045","Date":"7/7/2015","Time":"8:33am","Ask":"57.3100","Bid":"57.3045"},{"id":"USDSGD","Name":"USD/SGD","Rate":"1.3539","Date":"7/7/2015","Time":"8:33am","Ask":"1.3540","Bid":"1.3539"},{"id":"USDZAR","Name":"USD/ZAR","Rate":"12.4487","Date":"7/7/2015","Time":"8:33am","Ask":"12.4562","Bid":"12.4487"},{"id":"USDSEK","Name":"USD/SEK","Rate":"8.4844","Date":"7/7/2015","Time":"8:33am","Ask":"8.4852","Bid":"8.4844"},{"id":"USDCHF","Name":"USD/CHF","Rate":"0.9436","Date":"7/7/2015","Time":"8:33am","Ask":"0.9437","Bid":"0.9436"}]}}}
I think you'd be better off creating new rows instead of TD's:
var json = {"query":{"count":29,"created":"2015-07-07T07:33:27Z","lang":"nl-NL","results":{"rate":[{"id":"USDARS","Name":"USD/ARS","Rate":"9.1173","Date":"7/7/2015","Time":"8:33am","Ask":"9.1214","Bid":"9.1173"},{"id":"USDAUD","Name":"USD/AUD","Rate":"1.3374","Date":"7/7/2015","Time":"8:33am","Ask":"1.3376","Bid":"1.3374"},{"id":"USDBHD","Name":"USD/BHD","Rate":"0.3770","Date":"7/7/2015","Time":"8:33am","Ask":"0.3790","Bid":"0.3770"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.1391","Date":"7/7/2015","Time":"8:33am","Ask":"3.1392","Bid":"3.1391"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6428","Date":"7/7/2015","Time":"8:33am","Ask":"0.6428","Bid":"0.6428"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.2098","Date":"7/7/2015","Time":"8:33am","Ask":"6.2104","Bid":"6.2098"},{"id":"USDHRK","Name":"USD/HRK","Rate":"6.8687","Date":"7/7/2015","Time":"8:33am","Ask":"6.8988","Bid":"6.8687"},{"id":"USDDKK","Name":"USD/DKK","Rate":"6.7676","Date":"7/7/2015","Time":"8:33am","Ask":"6.7701","Bid":"6.7676"},{"id":"USDEGP","Name":"USD/EGP","Rate":"7.7327","Date":"7/7/2015","Time":"8:33am","Ask":"7.7352","Bid":"7.7327"},{"id":"USDSVC","Name":"USD/SVC","Rate":"8.7395","Date":"7/7/2015","Time":"8:33am","Ask":"8.7445","Bid":"8.7395"},{"id":"USDEEK","Name":"N/A","Rate":"N/A","Date":"N/A","Time":"N/A","Ask":"N/A","Bid":"N/A"},{"id":"USDETB","Name":"USD/ETB","Rate":"20.6850","Date":"7/7/2015","Time":"8:33am","Ask":"20.7880","Bid":"20.6850"},{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9070","Date":"7/7/2015","Time":"8:33am","Ask":"0.9070","Bid":"0.9070"},{"id":"USDHKD","Name":"USD/HKD","Rate":"7.7551","Date":"7/7/2015","Time":"8:33am","Ask":"7.7552","Bid":"7.7551"},{"id":"USDHUF","Name":"USD/HUF","Rate":"286.5400","Date":"7/7/2015","Time":"8:33am","Ask":"286.8600","Bid":"286.5400"},{"id":"USDINR","Name":"USD/INR","Rate":"63.3839","Date":"7/7/2015","Time":"8:33am","Ask":"63.3990","Bid":"63.3839"},{"id":"USDIDR","Name":"USD/IDR","Rate":"13298.0000","Date":"7/7/2015","Time":"8:33am","Ask":"13310.0000","Bid":"13298.0000"},{"id":"USDJPY","Name":"USD/JPY","Rate":"122.6850","Date":"7/7/2015","Time":"8:33am","Ask":"122.7000","Bid":"122.6850"},{"id":"USDKWD","Name":"USD/KWD","Rate":"0.3027","Date":"7/7/2015","Time":"8:33am","Ask":"0.3032","Bid":"0.3027"},{"id":"USDNZD","Name":"USD/NZD","Rate":"1.5032","Date":"7/7/2015","Time":"8:33am","Ask":"1.5035","Bid":"1.5032"},{"id":"USDNOK","Name":"USD/NOK","Rate":"8.1378","Date":"7/7/2015","Time":"8:33am","Ask":"8.1403","Bid":"8.1378"},{"id":"USDPKR","Name":"USD/PKR","Rate":"101.7300","Date":"7/7/2015","Time":"8:33am","Ask":"101.7600","Bid":"101.7300"},{"id":"USDPHP","Name":"USD/PHP","Rate":"45.1575","Date":"7/7/2015","Time":"8:33am","Ask":"45.1680","Bid":"45.1575"},{"id":"USDPLN","Name":"USD/PLN","Rate":"3.8149","Date":"7/7/2015","Time":"8:33am","Ask":"3.8180","Bid":"3.8149"},{"id":"USDRUB","Name":"USD/RUB","Rate":"57.3045","Date":"7/7/2015","Time":"8:33am","Ask":"57.3100","Bid":"57.3045"},{"id":"USDSGD","Name":"USD/SGD","Rate":"1.3539","Date":"7/7/2015","Time":"8:33am","Ask":"1.3540","Bid":"1.3539"},{"id":"USDZAR","Name":"USD/ZAR","Rate":"12.4487","Date":"7/7/2015","Time":"8:33am","Ask":"12.4562","Bid":"12.4487"},{"id":"USDSEK","Name":"USD/SEK","Rate":"8.4844","Date":"7/7/2015","Time":"8:33am","Ask":"8.4852","Bid":"8.4844"},{"id":"USDCHF","Name":"USD/CHF","Rate":"0.9436","Date":"7/7/2015","Time":"8:33am","Ask":"0.9437","Bid":"0.9436"}]}}};
var count = json.query.count,
created = json.query.created,
lang = json.query.lang;
for(i=0; i<json.query.results.rate.length; i++) {
var row = json.query.results.rate[i]; // Save a reference to the row.
$("<tr>").appendTo($("#result")) // Create new row, append it to the table's html.
.append('<td>' + count + '</td>') // Add all the data to the table.
.append('<td>' + created + '</td>')
.append('<td>' + lang + '</td>')
.append('<td>' + row.id + '</td>')
.append('<td>' + row.Name + '</td>')
.append('<td>' + row.Rate + '</td>')
.append('<td>' + row.Date + '</td>')
.append('<td>' + row.Time + '</td>')
.append('<td>' + row.Ask + '</td>')
.append('<td>' + row.Bid + '</td>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="result">
<tr>
<th>Count:</th>
<th>Created:</th>
<th>Lang:</th>
<th>Id:</th>
<th>Name:</th>
<th>Rate:</th>
<th>Date:</th>
<th>Time:</th>
<th>Ask:</th>
<th>Bid:</th>
</tr>
</table>
(I removed the console.log calls to make the answer a little shorter)
The vanilla js way would be to write a loop that inserts values into your table
Click Run code snippet to see the results
function createTd(text) {
var td = document.createElement('td');
td.textContent = text;
return td;
}
var data = [
{a: 1, b: 2, c: 3},
{a: 4, b: 5, c: 6},
{a: 7, b: 8, c: 9}
];
var table = document.querySelector('table');
data.forEach(function(row) {
var tr = document.createElement('tr');
tr.appendChild(createTd(row.a));
tr.appendChild(createTd(row.b));
tr.appendChild(createTd(row.c));
table.appendChild(tr);
});
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<tr>
<table>
All that DOM creation is a chore tho, right?
Here's a nice way to do it with React.
Click Run code snippet to see the results
table td {
font-size: 8pt;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<script type="text/jsx">
var data = JSON.parse('{"query":{"count":29,"created":"2015-07-07T07:36:44Z","lang":"en-US","results":{"rate":[{"id":"USDARS","Name":"USD/ARS","Rate":"9.1187","Date":"7/7/2015","Time":"8:35am","Ask":"9.1228","Bid":"9.1187"},{"id":"USDAUD","Name":"USD/AUD","Rate":"1.3371","Date":"7/7/2015","Time":"8:36am","Ask":"1.3374","Bid":"1.3371"},{"id":"USDBHD","Name":"USD/BHD","Rate":"0.3770","Date":"7/7/2015","Time":"8:35am","Ask":"0.3790","Bid":"0.3770"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.1391","Date":"7/7/2015","Time":"8:35am","Ask":"3.1392","Bid":"3.1391"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6429","Date":"7/7/2015","Time":"8:36am","Ask":"0.6429","Bid":"0.6429"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.2076","Date":"7/7/2015","Time":"8:36am","Ask":"6.2088","Bid":"6.2076"},{"id":"USDHRK","Name":"USD/HRK","Rate":"6.8681","Date":"7/7/2015","Time":"8:36am","Ask":"6.8982","Bid":"6.8681"},{"id":"USDDKK","Name":"USD/DKK","Rate":"6.7667","Date":"7/7/2015","Time":"8:36am","Ask":"6.7671","Bid":"6.7667"},{"id":"USDEGP","Name":"USD/EGP","Rate":"7.8323","Date":"7/7/2015","Time":"8:35am","Ask":"7.8550","Bid":"7.8323"},{"id":"USDSVC","Name":"USD/SVC","Rate":"8.7395","Date":"7/7/2015","Time":"8:35am","Ask":"8.7445","Bid":"8.7395"},{"id":"USDEEK","Name":"N/A","Rate":"N/A","Date":"N/A","Time":"N/A","Ask":"N/A","Bid":"N/A"},{"id":"USDETB","Name":"USD/ETB","Rate":"20.6850","Date":"7/7/2015","Time":"8:35am","Ask":"20.7880","Bid":"20.6850"},{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9069","Date":"7/7/2015","Time":"8:36am","Ask":"0.9070","Bid":"0.9069"},{"id":"USDHKD","Name":"USD/HKD","Rate":"7.7551","Date":"7/7/2015","Time":"8:36am","Ask":"7.7558","Bid":"7.7551"},{"id":"USDHUF","Name":"USD/HUF","Rate":"286.5950","Date":"7/7/2015","Time":"8:36am","Ask":"286.7000","Bid":"286.5950"},{"id":"USDINR","Name":"USD/INR","Rate":"63.3650","Date":"7/7/2015","Time":"8:36am","Ask":"63.3700","Bid":"63.3650"},{"id":"USDIDR","Name":"USD/IDR","Rate":"13305.0000","Date":"7/7/2015","Time":"8:36am","Ask":"13315.0000","Bid":"13305.0000"},{"id":"USDJPY","Name":"USD/JPY","Rate":"122.6800","Date":"7/7/2015","Time":"8:36am","Ask":"122.7000","Bid":"122.6800"},{"id":"USDKWD","Name":"USD/KWD","Rate":"0.3027","Date":"7/7/2015","Time":"8:35am","Ask":"0.3032","Bid":"0.3027"},{"id":"USDNZD","Name":"USD/NZD","Rate":"1.5029","Date":"7/7/2015","Time":"8:36am","Ask":"1.5033","Bid":"1.5029"},{"id":"USDNOK","Name":"USD/NOK","Rate":"8.1454","Date":"7/7/2015","Time":"8:36am","Ask":"8.1473","Bid":"8.1454"},{"id":"USDPKR","Name":"USD/PKR","Rate":"101.7300","Date":"7/7/2015","Time":"8:35am","Ask":"101.7600","Bid":"101.7300"},{"id":"USDPHP","Name":"USD/PHP","Rate":"45.1385","Date":"7/7/2015","Time":"8:35am","Ask":"45.1940","Bid":"45.1385"},{"id":"USDPLN","Name":"USD/PLN","Rate":"3.8152","Date":"7/7/2015","Time":"8:36am","Ask":"3.8156","Bid":"3.8152"},{"id":"USDRUB","Name":"USD/RUB","Rate":"57.3075","Date":"7/7/2015","Time":"8:36am","Ask":"57.3220","Bid":"57.3075"},{"id":"USDSGD","Name":"USD/SGD","Rate":"1.3536","Date":"7/7/2015","Time":"8:36am","Ask":"1.3537","Bid":"1.3536"},{"id":"USDZAR","Name":"USD/ZAR","Rate":"12.4555","Date":"7/7/2015","Time":"8:36am","Ask":"12.4569","Bid":"12.4555"},{"id":"USDSEK","Name":"USD/SEK","Rate":"8.4893","Date":"7/7/2015","Time":"8:36am","Ask":"8.4906","Bid":"8.4893"},{"id":"USDCHF","Name":"USD/CHF","Rate":"0.9435","Date":"7/7/2015","Time":"8:36am","Ask":"0.9436","Bid":"0.9435"}]}}}');
var Table = React.createClass({
renderRow: function(row) {
return (
<tr key={row.id}>
<td>{this.props.data.query.count}</td>
<td>{this.props.data.query.created}</td>
<td>{this.props.data.query.lang}</td>
<td>{row.id}</td>
<td>{row.Name}</td>
<td>{row.Rate}</td>
<td>{row.Date}</td>
<td>{row.Time}</td>
<td>{row.Ask}</td>
<td>{row.Bid}</td>
</tr>
);
},
render: function() {
return (
<table>
<tr>
<td>Count</td>
<td>Created</td>
<td>Lang</td>
<td>Id</td>
<td>Name</td>
<td>Rate</td>
<td>Date</td>
<td>Time</td>
<td>Ask</td>
<td>Bid</td>
</tr>
<tbody>
{this.props.data.query.results.rate.map(this.renderRow, this)}
</tbody>
</table>
)
}
});
React.render(<Table data={data} />, document.body);
</script>
You can do it dynamically by formatting your html like this
<table id='results'></table>
$.each(json.query.results.rate,function(i,item))
{
var table=$('#results'),
newRow = table.append($('<tr/>'));
for(var p in item){
newRow.append('<td>'+normalizeProperty(p)+'</td><td>'+item[p]+'</td>')
}
}
the normalizeProperty function is a function that allows you to convert properties into user-friendly names. Here is an example
function normalizeProperty(p){
p=p||"";
return p.replace('_','').toUppercase();
}

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

Categories

Resources