How to retrieve text content inside a table without any element id - javascript

I have a simple code of an html table. I need to write a Javascript function that is able to alert the content of any row that is selected using the mouse(by clicking).
I do not have any element id. So I need to use the event associated to the click of the mouse...
For example:
<tr>
<td onclick="...">Mamata</td>
<td>Sharma</td>
<td>20</td>
</tr>
I need to write a javascript function that is able to display with an alert any content of the table I select with a click.
For example If I click on 'Mamata', I need to see an alert appearing on the screen displaying 'Mamata'.

You can do it like this:
var td = document.getElementsByTagName("td");
for (var i = 0; i < td.length; i++) {
td[i].onclick = function() {
alert(this.innerHTML);
}
}
<table>
<tr>
<td>Mamata</td>
<td>Sharma</td>
<td>20</td>
</tr>
</table>

define this function
function alertContent(sender) {alert(sender.innerHTML);}
and use it in
onclick="javascript:alertContent(this)"

something like this,
<tr>
<td onClick="alert(this.innerHTML)">Mamata</td>
<td>Sharma</td>
<td>20</td>
</tr>
a better option is the following:
declare a function,
function alertcontent()
{
_sender = arguments.callee.caller.arguments[0].target;
if (_sender.tagName == "TD")
{
alert(_sender.innerHTML);
}
}
and assign this to the tables onclick event, like;
<table onclick="alertcontent()">
...
...
</table>
this way u can use less coding...

Here's a working solution - http://jsbin.com/wigolunowa/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table border=1>
<tr>
<td onClick="alert(this.innerHTML)">Mamata</td>
<td>Sharma</td>
<td>20</td>
</tr>
</table>
</body>
</html>

You can add a click handler to the table (once) and check which cell was clicked. The following example checks for cells (with "TD" tags) but can easily be changed to check for rows:
javascript
function showElementContent(event, table)
{
event = event || window.event;
for(var node = event.target || event.srcElement; node && node!= table; node = node.parentNode)
{ if(node.tagName == "TD")
break;
}
alert(node.innerText);
}
html
<table onclick="showElementContent(event, this)">
<tbody>
<tr><td>a cell</td>
<td>a cell with a <span>spanned element</span></td>
</tr>
</tbody>
</table>

You can just try adding an "OnClick" event to every single <td> with an alert to its innerHTML, something like this:
<td onclick="alert('Your value is '+this.innerHTML)">1</td>
<td onclick="alert('Your value is '+this.innerHTML)">ABC</td>
Or you can create JS function that loops through all the <td> cells (you select them by tag) and get their values:
var myCell = document.getElementsByTagName('td');
for(var i=0; i<=myCell.length; i++){
myCell[i].addEventListener('click', valueOnClick);
}
function valueOnClick(){
alert('Your value is '+this.textContent);
}

This is probably way too late to help but it's an approach not suggested by others and might be of use to someone else. At the very least it's an interesting way of using the DOM and "this" keyword to identify elements by relative positioning and not using an explicit element id.
Making a slight change to the HTML, use keyword "this" as an argument for your JavaScript function.
<table>
<tr>
<td onclick="myfunc(this)">Mamata</td>
<td>Sharma</td>
<td>20</td>
</tr>
</table>
The JavaScript function then takes advantage of the parent element/node to get the <tr> that the <td> resides within. Once we have the row we can get the number of cells and loop over each <td> element within the <tr> and get the text content within.
In the example below I'm assuming that the format for the alert message should just be a string of all the <td> elements on a row, but this would also be trivial to modify for a JSON or other format of output.
function myfunc(td_ele){
var td_row = td_ele.parentNode; //From button_ele get it's parentNode e.g. the <tr> element
var alert_msg = "";
//Iterate over the rows cell length
for(i=0; i<td_row.cells.length; i++){
alert_msg += td_row.cells[i].firstChild.textContent + " "; //stitch together alert_msg taking each rows cell child elements text
}
alert(alert_msg);
}

Related

JavaScript returns undefined for parent and children element

I am trying to select the parent element of a clicked button, and find the child elements text of that parent element however it is returning undefined.
var add = document.getElementById("add").parentElement.nodeName;
I found how we can access the parent element's node name, but I can't select it's child element by id.
Currently I am trying to get attributes for selected elements and user alert() to display them, however it's not working as expected. The code below is what I currently have:
window.onload = function(){
add();
}
function add() {
var add = document.querySelector(".add").parentNode;
var id = document.querySelector(".id").innerHTML;
var name = document.querySelector(".std").innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td class='id'>1</td><td class='std'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td class='id'>2</td><td class='std'>Sonam</td><td class='add'>ADD</td>
</tr>
</table>
</body>
</html>
There are two issues here:
you should use document.querySelector() when selecting a single element, rather than document.querySelectorAll() which is used to select multiple elements
the innerHTML field should be used instead of innerHtml
Note that document.querySelector() returns the first selected element (if any), where as document.querySelectorAll() returns a NodeList containing selected elements.
Here's a working snippet:
window.onload = function(){
add();
}
function add() {
var add = document.getElementById("add").parentNode;
/* Use querySelector for single element, and use innerHTML */
var id = document.querySelector("#id").innerHTML;
var name = document.querySelector("#std").innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td id='sn'>1</td><td id='name'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td id='id'>2</td><td id='std'>Sonam</td><td id='add'>ADD</td>
</tr>
</table>
</body>
</html>
Hope that helps
id attribute value must be unique across your HTML. So if you want to have multiple elements with the same identifier use class, also you need to know the index of the element you are targeting.
visit this link for more info about id attribute
You have a typo, the correct attribute is innerHTML not innerHtml and as mentioned before you need to know the index of the element
window.onload = function(){
add();
}
function add() {
var add = document.getElementById("add").parentNode;
var id = document.querySelectorAll("#id")[0].innerHTML;
var name = document.querySelectorAll("#std")[0].innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td id='sn'>1</td><td id='name'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td id='id'>2</td><td id='std'>Sonam</td><td id='add'>ADD</td>
</tr>
</table>
</body>
</html>

how to access table row object from an anchor within a cell?

i have a table with a few rows. i want to access the cells with the value that are in the same row as the anchor that triggers the function populateRow();
(i hope i explained it in a clear way).
any idea how to do that?
<tr>
<td>
some value
</td>
<td>
update
</td>
</tr>
<tr>
<td>
another value
</td>
<td>
update
</td>
</tr>
The populateRow() function would need to know which anchor was clicked, so you'd need to either pass this to it to give it a reference to said anchor:
onclick="populateRow(this);"
function populateRow(anchor) {
var row = $(anchor).closest("tr");
var firstCellValue = row.find("td").first().text();
}
...and from there use .closest() to navigate up the DOM to the containing tr element.
Or, better, bind the click event handler with jQuery rather than putting it inline on every row:
$(document).ready(function() {
$("#idOfYourTable").on("click", "a", function(e) {
var row = $(this).closest("tr");
var firstCellValue = row.find("td").first().text();
console.log(firstCellValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="idOfYourTable">
<tr>
<td>Value 1</td>
<td>
update
</td>
</tr>
<tr>
<td>Value 2</td>
<td>
update
</td>
</tr>
</table>
(Click the "Run..." button to see it working.)
I don't know what is that populateRow() function for, but if you want to get value on the first td of the same tr, then you can try testing this:
onclick="alert($(this).closest('tr').find('td:first').text())"
if you want to pass it in populateRow() function, you can:
onclick="populateRow($(this).closest('tr').find('td:first').text())"
Or ...
It would be more neat if you pass the element then process it later inside your function:
onclick="populateRow(this)"
function populateRow(elm) {
var val = $(elm).closest('tr').find('td:first').text();
alert(val);
}
Hope this helps. Good luck!

Swapping 2 html table elements

So I made this sliding puzzle using html, css and JavaScript:
this is a table and my question is how do I swap 2 table elements?
Let's say the one with the face (id = tile-2) and the white empy one (id = empty)
Hmm... try this:
https://jsfiddle.net/h7sp1ey8/
<button onclick='swap();'>
Swap
</button>
<table>
<tr>
<td id='f1'>
Contents of td 1
</td>
</tr>
<tr>
<td id='f2'>
Contents of t2
</td>
</tr>
</table>
<script>
function swap()
{
var f1 =document.getElementById('f1');
var f2=document.getElementById('f2');
var initialinner = f1.innerHTML;
f1.innerHTML=f2.innerHTML;
f2.innerHTML=initialinner;
}
</script>
Post your code if you want an exact solution. Here is how you program should work:
get id of box to swap
get id of box to swap to
swap them using method I gave in jsfiddle

Get data of first cell of clicked table row [duplicate]

This question already has answers here:
JavaScript - Get data of first cell of selected table row
(3 answers)
Closed 8 years ago.
<table border="1" cellpadding="5" id="newtable">
<tr>
<th>Room No</th>
<th>AC</th>
<th>Deluxe</th>
<th>Tariff</th>
</tr>
<c:forEach var="room" items="${myrooms}">
<tr bgcolor="#4B476F" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#4B476F';">
<td class="nr"><c:out value="${room.roomno}" /></td>
<td><c:out value="${room.ac}" /></td>
<td><c:out value="${room.deluxe}" /></td>
<td>₹<c:out value="${room.price}" /></td>
<td><button type="button" class="mybutton" onclick="rowFunction()">Pay</button> </td>
</tr>
</c:forEach>
</table>
On clicking the button corresponding to every row, I want my script to return the Room number i.e. the first cell data of the row. I have tried a lot of things after referring various articles on the Internet. Nothing seems to work. Please help. AND I REQUEST YOU TO POST NO JQUERY SOLUTIONS. ONLY JAVASCRIPT.
You can pass the clicked element to your function:
<td><button type="button" class="mybutton" onclick="rowFunction(this)">Pay</button> </td>
and traverse the DOM:
function rowFunction(el) {
var n = el.parentNode.parentNode.cells[0].textContent;
// ...
}
You can use the HTML5 function document.querySelectorAll to get a list of your buttons, then add an event listener to them that will allow you to access their parent row, and get its first cell.
var buttons = document.querySelectorAll('#newtable tbody .mybutton');
function buttonClicked(e) {
var button = this,
cell = button.parentElement,
row = cell.parentElement,
firstCell = row.querySelector('td');
alert(firstCell.innerHTML);
}
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', buttonClicked);
}
Here is the fiddle I used to verify my code. Also, consider using CSS instead of JavaScript to style your rows' color and hover color. It will be cleaner and more maintainable in the long term.
Use Like
$(".mybutton").click(function(){
alert($(this).parent().siblings().eq(0).text());
});
DEMO

Adding event handlers to each table row that will affect only that table row?

This isn't actually something I'm currently attempting to do; it just occurred to me while working with another table that I have no idea how I'd go about doing it, and the entire time on the train ride home I was puzzling over different solutions, none of which I could imagine working.
Imagine this situation: there is a table of 50 rows. On each row is a button. When clicked, this button should do something to the row it's on -- say, make all its text strikethrough, or make an AJAX call with the first cell's value, or something.
How would you go about binding those event handlers?
My initial thought was something like
buttons = document.getElementsByTagName("input");
rows = document.getElementsByTagName("tr");
for (i=0;i<buttons.length;i++) {
buttons[i].addEventListener('click',function() {
makeAjaxCall(rows[i]);
});
};
That is,
For each button in the document,
Add an event handler to that button,
Which will makeAjaxCall with the data of the row whose number corresponds to the button.
The problem, of course, being that makeAjaxCall will check the value of i when it's invoked, by which time, i is equal to buttons.length, and so the function will only ever work on the final row of the table.
So I suppose you'd need to find some way to actually hard-code the current value of i within the function handler... and that's something I don't even think is possible. Is it? How would you actually do something like this?
You can refer to the button object you are adding the event listener to using 'this'
Given the table in this format
<table>
<tr>
<td> <input type='button'> </td>
<td> 1st <td>
</tr>
<tr>
<td> <input type='button'> </td>
<td> 2nd <td>
</tr>
<tr>
<td> <input type='button'> </td>
<td> 3rd <td>
</tr>
</table>
The following code will allow you to access the data in the next cell, shown using console.log() rather than any ajax calls of course.
buttons = document.getElementsByTagName("input");
for (i=0;i<buttons.length;i++) {
buttons[i].addEventListener('click',function() {
makeAjaxCall(this);
});
};
function makeAjaxCall(btn) {
var sib=btn.parentNode.nextSibling;
while (sib.nodeName !='TD') {
sib=sib.nextSibling;
}
console.log(sib.innerHTML);
}
This can be extended to find any data in the row.
This section
while (sib.nodeName !='TD') {
sib=sib.nextSibling;
}
skips any extraneous characters (white space etc) between cells.
Fiddle Here
Interesting problem. I would go about doing it the way #kennebec suggests in the comment above.
Here is the fiddle: http://jsfiddle.net/u988D/
First, a slight change in markup to add data attributes
HTML
<table>
<tr>
<td data-to-json="id">1</td>
<td data-to-json="text">Lorem ipsum dolor.</td>
<td><button type="button">Click Me</button></td>
</tr>
<tr>
<td data-to-json="id">2</td>
<td data-to-json="text">Lorem ipsum dolor.</td>
<td><button type="button">Click Me</button></td>
</tr>
<tr>
<td data-to-json="id">3</td>
<td data-to-json="text">Lorem ipsum dolor.</td>
<td><button type="button">Click Me</button></td>
</tr>
</table>
Then the javascript. Probably can be optimized a bit more.
JS
var table = document.querySelector("table")
table.addEventListener("click", function(e) {
var element = e.target,
parent
//If the element is a button
if ( element && element.nodeName == "BUTTON" ) {
parent = element.parentNode
//Find the closest parent that is a TR
while ( parent.nodeName !== "TR" ) {
parent = parent.parentNode
}
//Convert Row to JSON
var json = {},
child
for ( var i = 0, _len = parent.children.length; i < _len; i++ ) {
child = parent.children[i]
if ( child.hasAttribute("data-to-json") ) json[child.getAttribute("data-to-json")] = child.innerText
}
// Do your AJAX stuff here
console.log(json)
}
})

Categories

Resources