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

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>

Related

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.

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

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>

HTML editable Table -> get edited Fields

I have a HTML-Table
<table style="width:100%">
<tr>
<th>id</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>2</td>
<td contenteditable="true">Smith</td>
<td contenteditable="true">50</td>
</tr>
<tr>
<td>3</td>
<td contenteditable="true">Jackson</td>
<td contenteditable="true">94</td>
</tr>
</table>
(Just a TEST-Table)
It is editable, but how do I get all the rows (with ID) which were edited, to send them to a PHP-Backend which saves the changes to DB?
Thanks in advance,
Patrick.
You can save ids in an Array whenever field content is changed.
Here is the Working Example: https://jsfiddle.net/79egs9tc/
var idArr = [];
$(".edited").focusout(function() {
var id = $(this).parent().attr('id');
if($.inArray(id, idArr) === -1){
idArr.push(id);
}
console.log(idArr);
});
You can add check for content is changes or not.
Hope, it will work for you.

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>

Categories

Resources