Javascript put data in columns table - javascript

I have a table which I want to put in the data that I get from ajax call in columns instead of rows here is the table body code
<tbody id="tableData-marketMonth">
<tr>
<th>Leads</th>
</tr>
<tr>
<th>Full Year Cost</th>
</tr>
<tr>
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr>
<th>Cost per Lead</th>
</tr>
</tbody>
Here is the JavaScript code that put the data into the table
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var tr =$("<tr/>");
tr.append($("<th/>",{
text : value.olxTotal
})).append($("<th/>",{
text : value.budget_total_year
})).append($("<th/>",{
text : value.budget_total_month
})).append($("<th/>",{
text : value.budget_per_lead
}))
$('#tableData-marketMonth').append(tr);
})
})
this is the current output
Desired output
Thank you very much

and I think I understood what you meant, probably best just to add id's to each <tr> and then append the value to them, like below.
HTML
<table>
<tbody id="tableData-marketMonth">
<tr id="leads">
<th>Leads</th>
</tr>
<tr id="fyc">
<th>Full Year Cost</th>
</tr>
<tr id="soc">
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr id="cpl">
<th>Cost per Lead</th>
</tr>
</tbody>
</table>
JQuery
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var leads = $('#leads');
var budget_total_year = $('#fyc');
var budget_total_month = $('#soc');
var budget_per_lead = $('#cpl');
leads.append('<td>' + value.olxTotal + '</td>');
budget_total_year.append('<td>' + value.budget_total_year + '</td>');
budget_total_month.append('<td>' + value.budget_total_month + '</td>');
budget_per_lead.append('<td>' + value.budget_per_lead + '</td>');
})
})

Related

Cannot read property 'mData' of undefined - Datatables [duplicate]

I have an issue with Datatables. I also went through this link which didn't yield any results. I have included all the prerequisites where I'm parsing data directly into the DOM.
Script
$(document).ready(function() {
$('.viewCentricPage .teamCentric').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bPaginate": false,
"bFilter": true,
"bSort": true,
"aaSorting": [
[1, "asc"]
],
"aoColumnDefs": [{
"bSortable": false,
"aTargets": [0]
}, {
"bSortable": true,
"aTargets": [1]
}, {
"bSortable": false,
"aTargets": [2]
}],
});
});
FYI dataTables requires a well formed table. It must contain <thead> and <tbody> tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.
The following will throw error (no <thead> and <tbody> tags)
<table id="sample-table">
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
<tr>
<td>data-1</td>
<td>data-2</td>
</tr>
</table>
The following will also throw an error (unequal number of columns)
<table id="sample-table">
<thead>
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>
For more info read more here
A common cause for Cannot read property 'fnSetData' of undefined is the mismatched number of columns, like in this erroneous code:
<thead> <!-- thead required -->
<tr> <!-- tr required -->
<th>Rep</th> <!-- td instead of th will also work -->
<th>Titel</th>
<!-- th missing here -->
</tr>
</thead>
<tbody>
<tr>
<td>Rep</td>
<td>Titel</td>
<td>Missing corresponding th</td>
</tr>
</tbody>
While the following code with one <th> per <td> (number of columns must match) works:
<thead>
<tr>
<th>Rep</th> <!-- 1st column -->
<th>Titel</th> <!-- 2nd column -->
<th>Added th</th> <!-- 3rd column; th added here -->
</tr>
</thead>
<tbody>
<tr>
<td>Rep</td> <!-- 1st column -->
<td>Titel</td> <!-- 2nd column -->
<td>th now present</td> <!-- 3rd column -->
</tr>
</tbody>
The error also appears when using a well-formed thead with a colspan but without a second row.
For a table with 7 colums, the following does not work and we see "Cannot read property 'mData' of undefined" in the javascript console:
<thead>
<tr>
<th>Rep</th>
<th>Titel</th>
<th colspan="5">Download</th>
</tr>
</thead>
While this works:
<thead>
<tr>
<th rowspan="2">Rep</th>
<th rowspan="2">Titel</th>
<th colspan="5">Download</th>
</tr>
<tr>
<th>pdf</th>
<th>nwc</th>
<th>nwctxt</th>
<th>mid</th>
<th>xml</th>
</tr>
</thead>
Having <thead> and <tbody> with the same numbers of <th> and <td> solved my problem.
I had this same problem using DOM data in a Rails view created via the scaffold generator. By default the view omits <th> elements for the last three columns (which contain links to show, hide, and destroy records). I found that if I added in titles for those columns in a <th> element within the <thead> that it fixed the problem.
I can't say if this is the same problem you're having since I can't see your html. If it is not the same problem, you can use the chrome debugger to figure out which column it is erroring out on by clicking on the error in the console (which will take you to the code it is failing on), then adding a conditional breakpoint (at col==undefined). When it stops you can check the variable i to see which column it is currently on which can help you figure out what is different about that column from the others. Hope that helps!
This can also occur if you have table arguments for things like 'aoColumns':[..] which don't match the correct number of columns. Problems like this can commonly occur when copy pasting code from other pages to quick start your datatables integration.
Example:
This won't work:
<table id="dtable">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<td>data 1</td>
<td>data 2</td>
</tbody>
</table>
<script>
var dTable = $('#dtable');
dTable.DataTable({
'order': [[ 1, 'desc' ]],
'aoColumns': [
null,
null,
null,
null,
null,
null,
{
'bSortable': false
}
]
});
</script>
But this will work:
<table id="dtable">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<td>data 1</td>
<td>data 2</td>
</tbody>
</table>
<script>
var dTable = $('#dtable');
dTable.DataTable({
'order': [[ 0, 'desc' ]],
'aoColumns': [
null,
{
'bSortable': false
}
]
});
</script>
One more reason why this happens is because of the columns parameter in the DataTable initialization.
The number of columns has to match with headers
"columns" : [ {
"width" : "30%"
}, {
"width" : "15%"
}, {
"width" : "15%"
}, {
"width" : "30%"
} ]
I had 7 columns
<th>Full Name</th>
<th>Phone Number</th>
<th>Vehicle</th>
<th>Home Location</th>
<th>Tags</th>
<th>Current Location</th>
<th>Serving Route</th>
Tips 1:
Refer to this Link you get some Ideas:
https://datatables.net/forums/discussion/20273/uncaught-typeerror-cannot-read-property-mdata-of-undefined
Tips 2:
Check following is correct:
Please check the Jquery Vesion
Please check the versiion of yours CDN or your local datatable related .min & css files
your table have <thead></thead> & <tbody></tbody> tags
Your table Header Columns Length same like Body Columns Length
Your Using some cloumns in style='display:none' as same propery apply in you both Header & body.
your table columns no empty, use something like [ Null, --, NA, Nil ]
Your table is well one with out <td>, <tr> issue
You have to remove your colspan and the number of th and td needs to match.
I faced the same error, when tried to add colspan to last th
<table>
<thead>
<tr>
<th> </th> <!-- column 1 -->
<th colspan="2"> </th> <!-- column 2&3 -->
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
and solved it by adding hidden column to the end of tr
<thead>
<tr>
<th> </th> <!-- column 1 -->
<th colspan="2"> </th> <!-- column 2&3 -->
<!-- hidden column 4 for proper DataTable applying -->
<th style="display: none"></th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
<!-- hidden column 4 for proper DataTable applying -->
<td style="display: none"></td>
</tr>
</tbody>
Explanaition to that is that for some reason DataTable can't be applied to table with colspan in the last th, but can be applied, if colspan used in any middle th.
This solution is a bit hacky, but simpler and shorter than any other solution I found.
I hope that will help someone.
in my case this error occured if i use table without header
<thead>
<tr>
<th>example</th>
</tr>
</thead>
I am getting a similar error. The problem is that the header line is not correct. When I did the following header line, the problem I was having was resolved.
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th colspan="6">Common Title</th>
</tr>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
</tbody>
</table>
Slightly different problem for me from the answers given above. For me, the HTML markup was fine, but one of my columns in the javascript was missing and didn't match the html.
i.e.
<table id="companies-index-table" class="table table-responsive-sm table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Created at</th>
<th>Updated at</th>
<th>Count</th>
</tr>
</thead>
<tbody>
#foreach($companies as $company)
<tr>
<td>{{ $company->id }}</td>
<td>{{ $company->name }}</td>
<td>{{ $company->created_at }}</td>
<td>{{ $company->updated_at }}</td>
<td>{{ $company->count }}</td>
</tr>
#endforeach
</tbody>
</table>
My Script:-
<script>
$(document).ready(function() {
$('#companies-index-table').DataTable({
serverSide: true,
processing: true,
responsive: true,
ajax: "{{ route('admincompanies.datatables') }}",
columns: [
{ name: 'id' },
{ name: 'name' },
{ name: 'created_at' },
{ name: 'updated_at' }, <-- I was missing this line so my columns didn't match the thead section.
{ name: 'count', orderable: false },
],
});
});
</script>
I had a dynamically generated, but badly formed table with a typo. I copied a <td> tag inside another <td> by mistake. My column count matched. I had <thead> and <tbody> tags. Everything matched, except for this little mistake I didn't notice for a while, because my column had a lot of link and image tags in it.
This one drove me crazy - how to render a DataTable successfully in a .NET MVC view. This worked:
**#model List<Student>
#{
ViewData["Title"] = "Index";
}
<h2>NEW VIEW Index</h2>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
#foreach (var element in Model)
{
<tr>
<td>#Html.DisplayFor(m => element.ID)</td>
<td>#Html.DisplayFor(m => element.FirstName)</td>
<td>#Html.DisplayFor(m => element.LastName)</td>
</tr>
}
</tbody>
</table>**
Script in JS file:
**$(document).ready(function () {
$('#example').DataTable();
});**
For those working in Webforms using GridView:
Moses's answer is totally correct. But since we're generating the table, the thead tag isn't generated by default. So to solve the problem add [YourGridViewID].HeaderRow.TableSection = TableRowSection.TableHeader to your backend, below of the DataBind() method call (if you're using it). This configuration takes the HeaderText value of the Field in your GridView as the value of the th tag it generates inside the thead.
In my case, and using ASP.NET GridView, UpdatePanel and with DropDownList (with Chosen plugin where I reset value to zero using a Javascript line), I got this error and tried everything with no hope for days. The problem was that the code of my dropdown in code behind was as follows and when I select a value twice to apply its action to selected grid rows I get that error. I thought for days it's a Javascript issue (again, in my case) and finally the fix was giving zero for the drowpdown value with the update process:
private void ddlTasks_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (ddlTasks.SelectedValue != 0) {
ChangeStatus(ddlTasks.SelectedValue);
ddlTasks.SelectedValue = "0"; //// **This fixed my issue**
}
dvItemsGrid.DataSource = CreateDatasource();
dvItemsGrid.DataBind();
dvItemsGrid.UseAccessibleHeader = true;
dvItemsGrid.HeaderRow.TableSection = TableRowSection.TableHeader;
}
This was my fault:
$('#<%= DropDownList.ClientID%>').val('0').trigger("chosen:updated").chosen();
I had encountered the same issue but I was generating table Dynamically. In my case, my table had missing <thead> and <tbody> tags.
here is my code snippet if it helped somebody
//table string
var strDiv = '<table id="tbl" class="striped center responsive-table">';
//add headers
var strTable = ' <thead><tr id="tableHeader"><th>Customer Name</th><th>Customer Designation</th><th>Customer Email</th><th>Customer Organization</th><th>Customer Department</th><th>Customer ContactNo</th><th>Customer Mobile</th><th>Cluster Name</th><th>Product Name</th><th> Installed Version</th><th>Requirements</th><th>Challenges</th><th>Future Expansion</th><th>Comments</th></tr> </thead> <tbody>';
//add data
$.each(data, function (key, GetCustomerFeedbackBE) {
strTable = strTable + '<tr><td>' + GetCustomerFeedbackBE.StrCustName + '</td><td>' + GetCustomerFeedbackBE.StrCustDesignation + '</td><td>' + GetCustomerFeedbackBE.StrCustEmail + '</td><td>' + GetCustomerFeedbackBE.StrCustOrganization + '</td><td>' + GetCustomerFeedbackBE.StrCustDepartment + '</td><td>' + GetCustomerFeedbackBE.StrCustContactNo + '</td><td>' + GetCustomerFeedbackBE.StrCustMobile + '</td><td>' + GetCustomerFeedbackBE.StrClusterName + '</td><td>' + GetCustomerFeedbackBE.StrProductName + '</td><td>' + GetCustomerFeedbackBE.StrInstalledVersion + '</td><td>' + GetCustomerFeedbackBE.StrRequirements + '</td><td>' + GetCustomerFeedbackBE.StrChallenges + '</td><td>' + GetCustomerFeedbackBE.StrFutureExpansion + '</td><td>' + GetCustomerFeedbackBE.StrComments + '</td></tr>';
});
//add end of tbody
strTable = strTable + '</tbody></table>';
//insert table into a div
$('#divCFB_D').html(strDiv);
$('#tbl').html(strTable);
//finally add export buttons
$('#tbl').DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
In addition to inconsistent and numbers, a missing item inside datatable scripts columns part can cause this too. Correcting that fixed my datatables search bar.
I'm talking about this part;
"columns": [
null,
.
.
.
null
],
I struggled with this error till I was pointed that this part had one less "null" than my total thead count.
in my case the cause of this error is i have 2 tables that have same id name with different table structure, because of my habit of copy-paste table code. please make sure you have different id for each table.
<table id="tabel_data">
<thead>
<tr>
<th>heading 1</th>
<th>heading 2</th>
<th>heading 3</th>
<th>heading 4</th>
<th>heading 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
<td>data-4</td>
<td>data-5</td>
</tr>
</tbody>
</table>
<table id="tabel_data">
<thead>
<tr>
<th>heading 1</th>
<th>heading 2</th>
<th>heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>
You need to wrap your your rows in <thead> for the column headers and <tbody> for the rows. Also ensure that you have matching no. of column headers <th> as you do for the td
I may be arising by aoColumns field. As stated HERE
aoColumns: If specified, then the length of this array must be equal
to the number of columns in the original HTML table. Use 'null' where
you wish to use only the default values and automatically detected
options.
Then you have to add fields as in table Columns
...
aoColumnDefs: [
null,
null,
null,
{ "bSortable": false },
null,
],
...
I found some "solution".
This code doesn't work:
<table>
<thead>
<tr>
<th colspan="3">Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
But this is ok:
<table>
<thead>
<tr>
<th colspan="2">Test</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
I think, that the problem is, that the last TH can't have attribute colspan.

Check if the element has text, if not add one

I have a simple table and I want to add specific text if an element is empty, so far my code looks like this:
$("table").each(function (index, tableID) {
$(tableID)
.find("thead tr th")
.each(function (index) {
index += 1;
$(tableID)
.find("tbody tr td:nth-child(" + index + ")")
.attr("data-title", $(this).text());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>By Year</th>
<th>TEAM</th>
<th>GP</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>GSW</td>
<td>6.1</td>
</tr>
<tr>
<th>2016-17</th>
<td>GSW</td>
<td>6.1</td>
</tr>
<tr>
<th>2015-16</th>
<td>GSW</td>
<td>6.1</td>
</tr>
</tbody>
</table>
With this code am adding data-title and everything works fine, what am trying to achieve to add - when there is no data: so I modify my code:
$( "table" ).each( function( index, tableID ) {
$( tableID ).find( "thead tr th" ).each( function( index ) {
index += 1;
$( tableID ).find( "tbody tr td:nth-child(" + index + ")" ).attr( "data-title", $(this).text() );
if ($("tbody tr td:nth-child(" + index + ")" ).is(':empty')).append( "-" );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>By Year</th>
<th>TEAM</th>
<th>GP</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>GSW</td>
<td>6.1</td>
</tr>
<tr>
<th>2016-17</th>
<td>GSW</td>
<td>6.1</td>
</tr>
<tr>
<th>2015-16</th>
<td>GSW</td>
<td>6.1</td>
</tr>
</tbody>
</table>
This part of code where am adding - when table element is empty doesn't work, can anybody try to help me with this?
Your if statement is not using valid syntax. You need the expression body after the if which contains the code to be executed. You cannot call a method from the if statement itself.
Try this:
$("table").each(function(_, table) {
$(table).find("thead tr th").each(function(i) {
let $th = $(this);
let $td = $(table).find("tbody tr td:nth-child(" + (i + 1) + ")");
$td.attr("data-title", $th.text());
if ($td.is(':empty')) {
$td.append("-");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>By Year</th>
<th>TEAM</th>
<th>GP</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>GSW</td>
<td>6.1</td>
</tr>
<tr>
<th>2016-17</th>
<td>GSW</td>
<td>6.1</td>
</tr>
<tr>
<th>2015-16</th>
<td>GSW</td>
<td>6.1</td>
</tr>
</tbody>
</table>
However, it's worth noting that this code can be made more succinct with a single line of code:
$('tbody td:empty').text('-');
The code you're using to loop through the th/td and add the data attribute seems almost entirely redundant as the th value can be read at the point of use.
I simplified the code a little. I found it easier to make the header data-title values an array i could reference each iteration. The '-' for empty values was just a ternary expression tacked on to the end of the jQuery chain:
$(this).attr("data-title", h[i]).text($(this).text() || "-");
$("table").each(function() {
let h = [], i = 0
$("thead tr th").each(function() {
h.push($(this).text());
})
$(this).find("tbody tr>*").each(function() {
$(this).attr("data-title", h[i]).text($(this).text() || "-");
i++;
if (i >= h.length) i = 0
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>By Year</th>
<th>TEAM</th>
<th>GP</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>GSW</td>
<td>6.1</td>
</tr>
<tr>
<th>2016-17</th>
<td>GSW</td>
<td>6.1</td>
</tr>
<tr>
<th>2015-16</th>
<td>GSW</td>
<td>6.1</td>
</tr>
</tbody>
</table>

Javascript grab the data from the table in the HTML and build an array of objects that contains the table data

I have an HTML table and I need to define a function that should grab the data from the table and build an array of objects that contains table data. Outside the function I have to declare a variable and assign the returned value from the function.
Thanks in advance.
HTML
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
JS
function buildTableData() {
let tbody = document.getElementsByTagName("tbody")[0];
let rows = tbody.children;
let people = [];
for (let row of rows) {
let person = {};
let cells = row.children;
person.rating = cells[0].textContent;
person.review = cells[1].textContent;
person.favoriteFood = cells[2].textContent;
people.push(person);
return people;
}
let data = people;
console.log(data);
}
You can get all the elements by using querySelectorAll('td'). Then use map to to get only the text of it and return this.
function buildTableData() {
const elements = [...document.querySelectorAll('td')];
return elements.map(x => {
return {content : x.innerHTML}
});
}
console.log(buildTableData());
<body>
<h2>Product reviews</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/7.3.1/acorn.js" integrity="sha512-4GRq4mhgV43mQBgKMBRG9GbneAGisNSqz6DSgiBYsYRTjq2ggGt29Dk5thHHJu38Er7wByX/EZoG+0OcxI5upg==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn-walk/7.2.0/walk.js" integrity="sha512-j5XDYQOKluxz1i4c7YMMXvjLLw38YFu12kKGYlr2+w/XZLV5Vg2R/VUbhN//K/V6LPKuoOA4pfcPXB5NgV7Gwg==" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
You can try using querySelectorAll() and map() like the following way:
function buildTableData() {
let rows = document.querySelectorAll('tbody tr');
let data = Array.from(rows).map(function(tr){
return {
rating: tr.querySelectorAll('td:nth-child(1)')[0].textContent,
review: tr.querySelectorAll('td:nth-child(2)')[0].textContent,
favoriteFood: tr.querySelectorAll('td:nth-child(3)')[0].textContent
};
});
console.log(data);
}
buildTableData();
<h2>Product reviews</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
You want a loop, and each review to be an object that is appended to an array of reviews is what I'm assuming
var reviews = [];
var tbody = document.querySelectorAll("tbody")[0];
var TRs = tbody.querySelectorAll("tr");
for (var a = 0; a < TRs.length; a++) {
var TDs = TRs[a].querySelectorAll("td");
var review = {
name: "",
rating: "",
review: ""
};
//These assume the order of your table columns don't change
review.name = TDs[0].innerHTML;
review.rating = TDs[1].innerHTML;
review.review = TDs[2].innerHTML;
reviews.push(review);
}
Your reviews array should have everything in there just as you wanted. I assumed the third column was "review" instead of "favorite food"

Wrong percentage of two number in the last td

I have a table that consists of <tr> and <td>'s and I show the percentage of the sold tickets in the third <td>.Also it suppost mytext as a number.My problem is the code calculates wrong percentage . i think this problem comes from html format such as space or tag.
What should i do?
here is my snippet :
$('table tbody tr').each(function() {
var $this = this,
td2Value = $('td:nth-child(2)', $this).text().trim().split(/\D+/);
$('span.result', $this).each(function (index, element) {
let v = $('td:nth-child(1)', $this).text().trim().split(/(\d+)/).filter(v => v);
if(v[index] != null && v[index].trim() == "Mytext")
{
v[index] = td2Value[index];
}
if(v[index] != null )
{
$(element).html(Math.round((td2Value[index] * 100 / v[index]) || 0) + '%');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th> avalable</th>
<th> sold</th>
<th> result </th>
</tr>
</thead>
<tbody>
<tr>
<td>
10<br/>Mytext<br/></td>
<td> 5<br/>2<br/></td>
<td>
<span class="result"></span><br/>
<span class="result"></span><br/>
</td>
</tr>
</tbody>
</table>
I think you should try this one.
$(element).html(Math.round((parseInt(td2Value[index]) * 100 / parseInt(v[index])) || 0) + '%');
and if you want answer in decimal you should try parseFloat() instead of parseInt()
You need to change your markup to keep 5 and 2 in different rows so that they are not picked up together as 52 while doing calculation.
Check this demo below.
$('table tbody tr').each(function() {
var $this = this,
td2Value = $('td:nth-child(2)', $this).text().trim().split(/\D+/);
$('span.result', $this).each(function(index, element) {
let v = $('td:nth-child(1)', $this).text().trim().split(/(\d+)/).filter(v => v);
if (v[index] != null && v[index].trim() == "Mytext") {
v[index] = td2Value[index];
}
if (v[index] != null) {
$(element).html(Math.round((td2Value[index] * 100 / v[index]) || 0) + '%');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th> avalable</th>
<th> sold</th>
<th> result </th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>5</td>
<td><span class="result"></span></td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td><span class="result"></span></td>
</tr>
</tbody>
</table>
You table tag's are wrong .Better change table like this.And add the js code like below.
calculate the percentage with cell one and two then post the result with 3rd cell
$('table tbody tr').each(function() {
var res = Math.round(parseInt($(this).find('td:eq(1)').text())/parseInt($(this).find('td:eq(0)').text())*100)
res = !isNaN(res) ? res :0
$(this).find('td:eq(2)').text(res+'%')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th> avalable</th>
<th> sold</th>
<th> result </th>
</tr>
</thead>
<tbody>
<tr>
<td> 10</td>
<td> 5</td>
<td> </td>
<tr>
<td>Mytext</td>
<td>2</td>
<td></td>
</tr>
</tbody>
</table>

Iterate over rows in JQuery Bootgrid table and extract values?

I am trying to iterate over a list of items in a Jquery Bootgrid table and extract the values to be used elsewhere. Here is my pseudo code:
for (each row in or-table) {
var code = the value in data-column-id="code";
var latitude = the value in data-column-id="lat";
var longitude = the value in data-column-id="long";
Console.log("code: " + code);
Console.log("latitude: " + latitude);
Console.log("longitude: " + longitude);
}
<table id="or-table" class="table table-condensed table-hover table-striped" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="code" >Symbol Code</th>
<th data-column-id="lat" >Latitude</th>
<th data-column-id="long" >Longitude</th>
</tr>
</thead>
<tbody></tbody>
</table>
I just want to loop through the rows in the table and save the values in the cells to a variable. I have been unable to find an example using Bootgrid.
You can loop through all the rows and access the elements there by which child it is.
$("#or-table tr").each(function(i, row){
var code = $(":nth-child(1)", row).html();
var latitude = $(":nth-child(2)", row).html();
var longitude = $(":nth-child(3)", row).html();
Console.log("code: " + code);
Console.log("latitude: " + latitude);
Console.log("longitude: " + longitude);
});
If not that, add class to each cell type like .code_value, .lat_value, .lng_value and access them in each() as $(row).find(".code_value").html().
Or find them by param name $(row).find("[data-column-id='code']").html()
This assumes your <td> elements have the data-column-id attributes:
$('tbody tr').each(function(idx, row) {
var code = $(row).find('[data-column-id="code"]').html();
var latitude = $(row).find('[data-column-id="lat"]').html();
var longitude = $(row).find('[data-column-id="long"]').html();
console.log("code: " + code);
console.log("latitude: " + latitude);
console.log("longitude: " + longitude);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="or-table" class="table table-condensed table-hover table-striped" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="code">Symbol Code</th>
<th data-column-id="lat">Latitude</th>
<th data-column-id="long">Longitude</th>
</tr>
</thead>
<tbody>
<tr>
<td data-column-id="code">1</td>
<td data-column-id="lat">2</td>
<td data-column-id="long">3</td>
</tr>
<tr>
<td data-column-id="code">4</td>
<td data-column-id="lat">5</td>
<td data-column-id="long">6</td>
</tr>
</tbody>
</table>
Even though you have selected an answer, the correct way to select all rows using the jQuery Bootgrid library is like this (Fiddle):
// The Rows from The Table
console.log(dt.data('.rs.jquery.bootgrid').rows)
//With Ajax + Pagination
console.log(dt.data('.rs.jquery.bootgrid').currentRows)
The DataTable:
<table id="employeeList" class="table table-bordered table-condensed table-hover">
<thead>
<tr>
<th data-column-id="iEmployeeId" data-type="numeric" data-visible="false" data-identifier="true" data-noresize>Id</th>
<th data-column-id="sName" data-order="desc">Name</th>
<th data-column-id="sAddress">Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>dsa</td>
<td>asd</td>
</tr>
<tr>
<td>2</td>
<td>sss</td>
<td>assd</td>
</tr>
<tr>
<td>3</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
<tr>
<td>4</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
<tr>
<td>5</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
<tr>
<td>6</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
<tr>
<td>7</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
<tr>
<td>8</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
<tr>
<td>9</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
<tr>
<td>10</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
<tr>
<td>11</td>
<td>asd</td>
<td>aaaaasd</td>
</tr>
</tbody>
</table>
Then initialize BootGrid Object:
var dt = $('#employeeList').bootgrid({
selection: true,
rowSelect: true,
converters: {},
});
Then Access the Rows and the Bootgrid DataTable Object
// the DT object
console.log(dt.data('.rs.jquery.bootgrid'))
// The Rows from The Table
console.log(dt.data('.rs.jquery.bootgrid').rows)
//With Ajax + Pagination
console.log(dt.data('.rs.jquery.bootgrid').currentRows)
var rows = dt.data('.rs.jquery.bootgrid').rows;
for(var i = 0; i < rows.length; i++)
{
console.log(rows[i].iEmployeeId);
console.log(rows[i].sName);
}
This code does not assume the position, order nor exclusivity of the th tags within each set of tr tags.
$("tr").each(function(row){
var code = row.find("th[data-column-id='code']").text()
var latitude = row.find("th[data-column-id='lat']").text()
var longitude = row.find("th[data-column-id='long']").text()
Console.log("code: " + code);
Console.log("latitude: " + latitude);
Console.log("longitude: " + longitude);
});
I think you are looking for the BootGrid select method.
http://www.jquery-bootgrid.com/Documentation#methods
var rows = $("#or-table").bootgrid("select");

Categories

Resources