How to iterate through each data in a table - javascript

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

Related

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"

How can I get only one column value from html table?

I have a html table that shows a list of users ID, Name and E-mail. When my user clicks in any row, I get the id number of that row and send to my backend. So, I did this:
//Making the table
var trs = document.getElementsByTagName('tr');
for (var i = 0; i < trs.length; i++) {
trs[i].onclick = clickHandler;
}
Function that handles the click:
function clickHandler(event) {
var numb = this.innerText.match(/\d/g);
numb = numb.join("");
window.location.replace("chooseParticipant.php?id="+numb);
}
Table Example:
<div id="table">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<td>7</td>
<td>Test User</td>
<td>testuser123#example.com</td>
</tbody>
</table>
</div>
What happens then? If an user have numbers in their e-mail, the "numb" variable gets these numbers too. I don't know how to filter only the id number. Did someone have any ideas?
You could assign a class to you tag.
Something like below:-
<td class="id">7</td>
And in the javascript code you could fetch all the elements with class "id".
And then perform your click handler on each one.
var trs = document.getElementsByClassName('id');
I hope this helps.
Try this code snippet which use data-* attribute
document.addEventListener('DOMContentLoaded', function(e) {
var trs = document.querySelectorAll('#table tbody tr');
var repeater = Array.prototype.slice;
repeater.call(trs).forEach(function(tr) {
tr.addEventListener('click', function(e) {
var data = tr.querySelector('td[data-id]').dataset;
console.log('id=', data.id);
});
});
});
tbody {
cursor: pointer;
}
<div id="table">
<table border="1" cellspacing="0" cellpadding="3">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="7">7</td>
<td>Test User 1</td>
<td>testuser1231#gmail.com</td>
</tr>
<tr>
<td data-id="8">8</td>
<td>Test User 2</td>
<td>testuser1232#gmail.com</td>
</tr>
<tr>
<td data-id="9">9</td>
<td>Test User 3</td>
<td>testuser1233#gmail.com</td>
</tr>
</tbody>
</table>
</div>

How can you target a child element of an iterated object in JavaScript?

In this instance I simply want to target tables that have a thead tag.
I trying to concatenate or search using JavaScript or jQuery whichever is quicker.
e.g thead = DT[i].children('thead');
function go() {
var i = 0,
DT = document.getElementsByClassName('DT');
for (i; i < DT.length; ++i) {
var x = DT[i];
if ($(x + ' thead').length) {
//do stuff to this table
}
}
}
<table class="DT" id="gv1">
<tbody>
<tr>
<th>th</th>
</tr>
<tr>
<td>td</td>
</tr>
</tbody>
</table>
<table class="DT" id="gv2">
<thead>
<tr>
<th>thead</th>
</tr>
</thead>
<tbody>
<tr>
<td>td</td>
</tr>
</tbody>
</table>
You don't need any loops, you can use jQuery's :has() selector to retrieve an element based on whether or not it contains a specified child, like this:
function go() {
$('.DT').has('thead').addClass('foo');
}
go();
.foo { border: 1px solid #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="DT" id="gv1">
<tbody>
<tr>
<th>th</th>
</tr>
<tr>
<td>td</td>
</tr>
</tbody>
</table>
<table class="DT" id="gv2">
<thead>
<tr>
<th>thead</th>
</tr>
</thead>
<tbody>
<tr>
<td>td</td>
</tr>
</tbody>
</table>
You can use querySelector to check if the nested thead exists.
if (x.querySelector("thead")) {
//do stuff to this table
}
Just so you know, you'd do this to accomplish what you were trying originally:
if ($(x).find("thead").length) {
//do stuff to this table
}
This is just to show how you can perform DOM selection from a given context.

HTML Table onClick function to get table row key and value

I wanted to create a HTML table with onclick function to get the key and value of a row, so far the onclick function is working but it displaying and empty array for me, how can I fix this problem. Thanks.
I wanted it to be display in console log in this format when you click on the first row:
{ "name":"Clark", "age":29};
Here is my code
var table = document.getElementById("tableID");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
tableText(this);
};
}
}
function tableText(tableRow) {
var myJSON = JSON.stringify(tableRow);
console.log(myJSON);
}
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<tr>
<th hidden="hidden"></th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td >Clark</td>
<td>29</td>
</tr>
<tr>
<td >Bruce</td>
<td>30</td>
</tr>
</tbody>
</table>
I edited my answer to return the data as an object. Run the script and have a look.
var table = document.getElementById("tableID");
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
tableText(this);
};
}
}
function tableText(tableRow) {
var name = tableRow.childNodes[1].innerHTML;
var age = tableRow.childNodes[3].innerHTML;
var obj = {'name': name, 'age': age};
console.log(obj);
}
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<tr>
<th hidden="hidden"></th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td >Clark</td>
<td>29</td>
</tr>
<tr>
<td >Bruce</td>
<td>30</td>
</tr>
</tbody>
</table>
I think you can use tr.innerTestto get the value in the tags
If you are using jQuery you can add an eventlistener to the table like this
$('#tableID').on('click', 'tr', function(e){
tableText($(this).html());
});
function tableText(tableRow) {
var myJSON = JSON.stringify(tableRow);
console.log(myJSON);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<tr>
<td>Text</td>
<td>MoreText</td>
<td>Lorem</td>
<td>Ipsum</td>
</tr>
<tr>
<td>Text</td>
<td>MoreText</td>
<td>Lorem</td>
<td>Ipsum</td>
</tr>
<tr>
<td>Text</td>
<td>MoreText</td>
<td>Lorem</td>
<td>Ipsum</td>
</tr>
<tr>
<td>Text</td>
<td>MoreText</td>
<td>Lorem</td>
<td>Ipsum</td>
</tr>
</table>
There are many ways to do what you're after, however a robust and extensible way would be to get the property names from the table header row, then get the values from the row that was clicked on.
I don't know why you have hidden cells in the header, it just complicates things. If you're using it for data, that would be much better in an associated object or data-* property of the table or row.
function getRowDetails(event) {
row = this;
var table = row.parentNode.parentNode;
var header = table.rows[0];
// Get property names from header cells
var props = [].reduce.call(header.cells, function(acc, cell ) {
if (!cell.hasAttribute('hidden')) {
acc.push(cell.textContent);
}
return acc;
}, []);
// Get value for each prop from data cell clicked on
var result = props.reduce(function(acc, prop, i) {
acc[prop] = row.cells[i].textContent;
return acc;
}, {});
// Do something with result
console.log(result);
return result;
}
// Add listener to body rows, could also put single listener on table
// and use event.target to find row
window.onload = function() {
[].forEach.call(document.getElementsByTagName('tr'), function(row, i) {
if (i) row.addEventListener('click', getRowDetails, false);
});
}
<table align="center" id="tableID" border="1">
<thead>
<tr><th hidden="hidden"></th><th>name</th><th>age</th></tr>
</thead>
<tbody style="cursor: pointer;">
<tr><td >Clark</td><td>29</td></tr>
<tr><td >Bruce</td><td>30</td></tr>
</tbody>
</table>

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

Categories

Resources