Click table row and get value of all cells
There is no need to add ids or add multiple event handlers to the table. One click event is all that is needed. Also you should use thead and tbody for your tables to separate the heading from the content.
var table = document.getElementsByTagName("table")[0];var tbody = table.getElementsByTagName("tbody")[0];tbody.onclick = function (e) { e = e || window.event; var data = []; var target = e.srcElement || e.target; while (target && target.nodeName !== "TR") { target = target.parentNode; } if (target) { var cells = target.getElementsByTagName("td"); for (var i = 0; i < cells.length; i++) { data.push(cells[i].innerHTML); } } alert(data);};
<table class='list'> <thead> <tr> <th class='tech'>OCB</th> <th class='area'>Area</th> <th class='name'>Name</th> <th class='cell'>Cell #</th> <th class='nick'>Nickname</th> </tr> </thead> <tbody> <tr> <td>275</td> <td>Layton Installation</td> <td>Benjamin Lloyd</td> <td>(801) 123-456</td> <td>Ben</td> </tr> </tbody></table>
Getting row information from click on a table cell
Indexing out of, then back into the element seemed to do the trick.
let tr = star.parentElement.parentElement;
let id = tr.children[0].innerHTML;
let product_name = tr.children[2].innerHTML;
get table cell value using jquery on row click
Pass the incidentId
instead of this
to inline click handler
<tr onclick="changeIncidentValue(${incident.incidentId})">
instead of
<tr onclick="changeIncidentValue(this)">
Or, As you are passing this
, use it with DOM traversal method to get the value from first TD element
function changeIncidentValue(elem){
$('#incidentId').val($(elem).find('td:first').text());
}
HTML Table onClick function to get table row key and value
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>
How to get table row value into text field in JavaScript..?
I don't know exactly what you're trying to do, but it's not working because your click listener is being called before your table is populated. See my code.
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
setListeners();
}
var table = document.getElementById('tblk'),
rIndex;
function setListeners() {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].addEventListener('click', function (e) {
console.log(e.target);
document.getElementById('InputCusomerID').value = "result: " + this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = "result: " + this.cells[1].innerHTML
document.getElementById('InputItemID').value = "result: " + this.cells[2].innerHTML
});
}
}
addRow();
<input type="text" id="InputCusomerID" value="a" />
<input type="text" id="InputCusomerName" value="b" />
<input type="text" id="InputItemID" value="c" />
<table class="table table-green table-hover" id="tblk"></table>
Get the contents of a table row with a button click
The object of the exercise is to find the row that contains the information. When we get there, we can easily extract the required information.
Answer
$(".use-address").click(function() {
var $item = $(this).closest("tr") // Finds the closest row <tr>
.find(".nr") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$("#resultas").append($item); // Outputs the answer
});
VIEW DEMO
Now let's focus on some frequently asked questions in such situations.
How to find the closest row?
Using .closest()
:
var $row = $(this).closest("tr");
Using .parent()
:
You can also move up the DOM tree using .parent()
method. This is just an alternative that is sometimes used together with .prev()
and .next()
.
var $row = $(this).parent() // Moves up from <button> to <td>
.parent(); // Moves up from <td> to <tr>
Getting all table cell <td>
values
So we have our $row
and we would like to output table cell text:
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td"); // Finds all children <td> elements
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
VIEW DEMO
Getting a specific <td>
value
Similar to the previous one, however we can specify the index of the child <td>
element.
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
VIEW DEMO
Useful methods
.closest()
- get the first element that matches the selector.parent()
- get the parent of each element in the current set of matched elements.parents()
- get the ancestors of each element in the current set of matched elements.children()
- get the children of each element in the set of matched elements.siblings()
- get the siblings of each element in the set of matched elements.find()
- get the descendants of each element in the current set of matched elements.next()
- get the immediately following sibling of each element in the set of matched elements.prev()
- get the immediately preceding sibling of each element in the set of matched elements
Get HTML table cells values in a rows by clicking on it
You can use event.target.innerText for javascript and $(event.target).text() for jQuery, jQuery is preferred solution as it handles cross browser competibilities.
Using only javascript
Live Demo
Html
<table id="tableID" onclick="myFun(event)" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Javascript
function myFun(e){
alert(e.target.innerText); //current cell
alert(e.target.parentNode.innerText); //Current row.
}
Using jQuery
Live Demo
Html
<table id="tableID" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Javascript
$('#tableID').click(function(e){
alert($(e.target).text()); // using jQuery
})
Javascript get table cell content on click
Add a single listener to the tbody of the table, and retrieve the clicked cell from the event object, like this:
const tbody = document.querySelector('#position tbody');tbody.addEventListener('click', function (e) { const cell = e.target.closest('td'); if (!cell) {return;} // Quit, not clicked on a cell const row = cell.parentElement; console.log(cell.innerHTML, row.rowIndex, cell.cellIndex);});
<table id="position"> <tr> <td>TL</td> <td>TC</td> <td>TR</td> </tr> <tr> <td>CL</td> <td>CC</td> <td>CR</td> </tr> <tr> <td>BL</td> <td>BC</td> <td>BR</td> </tr></table>
How do I get the value of a cell in an HTML table on click of a row from a dynamically generated table without using buttons or tbody
You can bind a click event to an existing element on the page and get the value of the first cell using DOM navigation. So, for example, if your table already existed on the page and you want to bind a click event to dynamically added rows, you can reference the table
element:
$(document).ready(function() {
$('table').on('click', 'tr', function() {
var value = $(this).find('td:first-child').text();
//do something with value
});
});
Demo
In your case, it looks like you're dynamically adding the table itself to the page. In that case, you can bind to document
and reference the id of the dynamically added table:
$(document).ready(function() {
$('document').on('click', '#order-table tr', function() {
var value = $(this).find('td:first-child').text();
//do something with value
});
});
If you want this click event on all tables, you can do:
$(document).ready(function() {
$('document').on('click', 'table tr', function() {
var value = $(this).find('td:first-child').text();
//do something with value
});
});
Related Topics
JavaScript Image Overlay Over a Specified Div
Bootstrap 3.0 Popovers and Tooltips
Horizontal Swipe Slider with Jquery and Touch Devices Support
How to Copy Multiple Files and Keep the Folder Structure with Gulp
How to Get Jquery or JavaScript to Change CSS Based on the Current Url
Send a Notification from JavaScript in Uiwebview to Objectivec
Animation for Newly Rendered Elements, But Not on Page Load
How to More Accurately Measure Svg Text Height
How to Open Blob Url on Chrome iOS
Android Webview, Loading JavaScript File in Assets Folder
How to Detect When a CSS File Has Been Fully Loaded
Ng If with Angular for String Contains
Facebook Oauth "Unsupported" in Chrome on iOS
Performance Difference Between JavaScript Created Inline Styles and JavaScript Created Stylesheets