Iterate over rows in JQuery Bootgrid table and extract values? - javascript

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

Related

Javascript put data in columns table

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

How to iterate through each data in a table

<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
I am a bit confused about how to get all the data from the table using a single button. When the user click on the button i should get all the table data. I tried with the below code. I need to get all the data in a array format. So that i can save all the data to my database.
$("#saveButton").click(function(event) {
var table = document.getElementById("table");
var dataArray = [];
var data = table.find('td');
for (var i = 0; i <= data.size() - 1; i = i + 4) {
data.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}
});
Try this code.
$("#saveButton").click(function(event) {
var data = [];
$("#table tr").each(function(i){
if(i != 0){
data.push({
id: $(this).find("td:eq(0)").html(),
name: $(this).find("td:eq(1)").html(),
email: $(this).find("td:eq(2)").html(),
phone: $(this).find("td:eq(3)")}).html()
});
}
});
//do something with data
});
If you want to use jquery, have a look at https://jsfiddle.net/qg6xpy39/
HTML:
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
<button id="saveButton">
click
</button>
JS:
$("#saveButton").click(function(event) {
var rows = $('#table td'); // retrieve the rows of your table
var dataArray = [];
$.each(rows, function(idx, elt) {
dataArray.push($(elt).text()); // add cell text content to the data array
});
console.log(dataArray); // so you can check what's in the array ;-)
});
As said in comments, in plain JavaScirpt.
use querySelectorAll to select all trs. Then iterate in each of them and get it's td's innerHTML and push it in an array.
Then use Array.shift() to remove the th elements. That is, the titles.
The code
function save(){
var arr=[];
var tr=document.querySelectorAll('tr');
tr.forEach(function(x,y){
arr[y]=[];
x.querySelectorAll("td").forEach(function(z){
arr[y].push(z.innerHTML);
});
});
arr.shift();
console.log(arr);
}
Check the below snippet.
function save(){
var arr=[];
var tr=document.querySelectorAll('tr');
tr.forEach(function(x,y){
arr[y]=[];
x.querySelectorAll("td").forEach(function(z){
arr[y].push(z.innerHTML);
});
});
arr.shift();
console.log(arr);
}
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
<button onclick="save();">Save</button>
Another possible approach, again using pure javascript rather than jQuery would be to use the DOM NodeIterator in conjunction with an XPath via Document.evaluate()
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Javascript DOM Processing</title>
<script type='text/javascript'>
document.addEventListener('DOMContentLoaded',function(e){
var query='/html/body/table[#id="table"]/tbody/tr/td';
var xpr = document.evaluate( query, document, null, XPathResult.ANY_TYPE, null );
var td = xpr.iterateNext();
var dataTbl=[];
while( td ){
try{
dataTbl.push( td.textContent );
td=xpr.iterateNext();
}catch( err ){
alert( 'Error'+err );
}
}
/* The data from all table cells is now in the array */
alert( dataTbl.join(String.fromCharCode(10)) );
},false);
</script>
</head>
<body>
<!-- content -->
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
</body>
</html>
Simplest approach would be
var data_arr = [];
$('#table tr').each(function() {
data_arr.push(this.cells[0].innerHTML);
data_arr.push(this.cells[1].innerHTML);
data_arr.push(this.cells[2].innerHTML);
data_arr.push(this.cells[3].innerHTML);
});

Trying to combine the rows having 3 columns same and 1 different column into one row javascript jquery

I am trying to combine the the rows having same into one column.
Suppose my th are id,name
Suppose am having like
1 ram
1 raj
then I want output as
1 ram,raj
ram,raj should be displayed in text area
Am getting the data using youtube api
<table class="table table-bordered" style="width:90%">
<thead>
<tr>
<th>id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>ram</td>
<tr>
<tr>
<td>1</td>
<td>raj</td>
<tr>
Give ID to your Table Like this:-
<table class="table table-bordered" id="example" style="width:90%">
<thead>
<tr>
<th>id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>ram</td>
<tr>
<tr>
<td>1</td>
<td>raj</td>
<tr>
</table>
And in your Jquery code you can get String Like this:-
var str = "";
var table = $("#example");
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'), examplestring = $tds.eq(1).text();
if(str=="")
{
str = examplestring;
}
else
{
str = str + "," + examplestring;
}
});
console.log(str);
});
Where str contains your string

How to copy the contents of one row in a table to another table and add the identical ones

var Sell_Button = document.getElementById('sellbtn'),
secondTable = document.getElementById("secondTableBody");
Sell_Button.addEventListener('click', function() {
var Row = secondTable.insertRow();
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[2].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
//checks to see if the secondTable has a row containing the same name
for (var f = 0; f < secondTable.rows.length; f += 1) {
//adds only the sold amount if the second table has a row with the same name
//error
if (secondTable.rows[f].cells[0].innerText === this.parentNode.parentNode.cells[0].innerText) {
secondTable.rows[f].cells[1].innerHTML = +this.parentNode.parentNode.cells[2].innerHTML;
//deletes an extra row that is added at the bottom
if (secondTable.rows.length > 1) {
secondTable.deleteRow(secondTable.rows.length - 1);
}
//if nothing matched then a new row is added
} else {
secondTable.insertRow();
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[2].innerHTML;
}
}
}
}
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Ok, this example isn't exactly what i'm working on but it's very similar. The only difference is that in mine the rows and buttons are dynamically added by the user and he inserts the details. What I want is that when i press on the button of each row (sell) the details (Item and Sold only) are copied into a row in the second table and checks if the same item exists in this second table if so then it adds the amount of sold of both items in one row. For instance I press on the first row button the Apples it copies the listed above details to the second table in a row and then when i click on the button of the second row (Apples also) it only adds the sold amount up and doesn't add a second apples row because an apples row already exists in the second table but when i click on the oranges button it makes a new row because the oranges row doesn't exist. So how do I do this in JavaScript? i hope i was thorough and made any sense. I have no idea why the code isn't working here but i hope you get the point. This code works perfectly just as i want it to until for some reason i get this error: Cannot read property 'innerText' of undefined when i press the buttons approx. 6-7 times targeting the if statement where i commented error.
This sets a click handler to all buttons. If the row doesn't exist in the second table it's created. It sets a data-type referring to the item. When somebody clicks the sell button again and there is a row containing the data-type the row is updated instead of created. All in plain JavaScript.
var Sell_Button = document.querySelectorAll('.sellbtn'),
secondTable = document.getElementById("secondTableBody");
Array.prototype.slice.call(Sell_Button).forEach(function(element){
element.addEventListener('click', function(e) {
//since the button is an element without children use e.
var clickedElement = e.target;
var parentRow = clickedElement.parentNode.parentNode;
//check if second table has a row with data-type
var rowWithData = secondTable.querySelector("[data-type='"+parentRow.cells[0].childNodes[0].nodeValue+"']");
if (rowWithData)
{
rowWithData.cells[1].innerHTML = parseInt(rowWithData.cells[1].childNodes[0].nodeValue) + parseInt(parentRow.cells[2].childNodes[0].nodeValue);
}
else
{
var Row = secondTable.insertRow();
Row.setAttribute("data-type", parentRow.cells[0].childNodes[0].nodeValue);
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = parentRow.cells[0].childNodes[0].nodeValue;
Row.cells[1].innerHTML = parentRow.cells[2].childNodes[0].nodeValue;
}
});
});
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Do you mean something like:
$(document).on("click", "#firstTable tr button", function(b) {
b = $(this).closest("tr");
var d = $.trim(b.find("td:first").text());
b = parseFloat($.trim(b.find("td:nth-child(3)").text()));
var a = $("#secondTable"),
c = a.find("tr").filter(function(a) {
return $.trim($(this).find("td:first").text()) == d
});
c.length ? (a = c.find("td:nth-child(2)"), c = parseFloat($.trim(a.text())), a.text(b + c)) : (a = $("<tr />").appendTo(a), $("<td />", {
text: d
}).appendTo(a), $("<td />", {
text: b
}).appendTo(a))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<tr>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</tr>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td><button>Sell</button></td>
</tr>
</tbody>
</table>
</div>
<br />
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<tr>
<th>Item</th>
<th>Sold</th>
</tr>
</thead>
<tbody id="secondTableBody"></tbody>
</table>
</div>

Unable to delete column with cells

I am not able to delete the column with all the cells. It works fine if i try to delete the last column but if i try to delete the column before last, it does not work as expected.
This is how my HTML looks like:
<table id="tblData">
<thead>
<tr style="background-color:green" id="trMain">
<th>Fixed 1</th>
<th>Fixed 2</th>
<th>Fixed 3</th>
<th id="Collection1">Collection 1</th>
<th id="Collection2">Collection 2</th>
</tr>
<tr style="background-color:red" id="trSub">
<th>E1</th>
<th>E2</th>
<th>E3</th>
<th>
<table>
<thead>
<tr>
<th>P1</th>
<th>P2</th>
<th>P3</th>
</tr>
</thead>
</table>
</th>
<th>
<table>
<thead>
<tr>
<th>P1</th>
<th>P2</th>
<th>P3</th>
</tr>
</thead>
</table>
</th>
</tr>
</thead>
</table>
<button type="button" id="btnGet">Delete a Column</button>
This is how my JS looks like:
$(document).ready(function () {
var colToDelete = 'Collection2';
$('#btnGet').click(function(){
var column = $("#tblData").find('#' + colToDelete);
var row = column.parent('tr').children();
var idx = row.index(column);
alert(idx)
$("#trMain").find("th:eq(" + idx + ")").remove();
alert(idx)
$("#trSub").find("th:eq(" + idx + ")").remove();
});
});
Here is the JS Fiddle: http://jsfiddle.net/cH654/
i have updated your script, this should work
$(document).ready(function () {
var colToDelete = 'del1';
$('#btnGet').click(function(){
var column = $("#tblData").find('#' + colToDelete);
var row = column.parent('tr').children();
var idx = row.index(column);
$("#trMain").find("th:eq(" + idx + ")").remove();
$("#trSub > th:eq(" + idx + ")").remove();
});
});
You have problems because you put a table within a table, so the columns of your two rows doesn't correspond. Your second row should be like this:
<tr style="background-color:red" id="trSub">
<th>E1</th>
<th>E2</th>
<th>E3</th>
<th>P1 P2 P3</th>
<th>P1 P2 P3</th>
</tr>
And your jquery function should be as simple as this:
$('#btnGet').click(function(){
$("#trMain th").last().remove();
$("#trSub th").last().remove();
});
Here is working: http://jsfiddle.net/cH654/5/

Categories

Resources