Get HTML table cells values in a rows by clicking on it - javascript

How can I get values of TDs inside an HTML table?
i.e.
| ID | cell 1 | cell 2 |
| 1 | aaaa | a2a2a2 |
| 2 | bbbb | b2b2b2 |
| 3 | cccc | c2c2c2 |
So now if I click on the cell value: "bbbb" I want to get all the values of selected row:
$id='2'; $cell_1='bbbb'; $cell_2='b2b2b2';
NOTE: I'd like to use JavaScript and not jQuery.

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

var table = document.getElementById('tableID'),
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++){
cells[i].onclick = function(){
console.log(this.innerHTML);
/* if you know it's going to be numeric:
console.log(parseInt(this.innerHTML),10);
*/
}
}
from here

Hope This helps you. It contains cross browser script.
<html>
<head>
<script type="text/javascript">
function myFun(e){
if(!e.target)
alert(e.srcElement.innerHTML);
else
alert(e.target.innerHTML);
}
</script>
</head>
<body>
<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>
</body>
</html>

Use of jquery will be easy..
$("#tableId").find("td").click(function(event){
var listOfCell=$(this).siblings();
for(i=0;i<listOfCell.length;i++){
alert($(listOfCell[i]).text());
}
});

Related

How to delete all columns of a row using Javascript

I have the following code to delete the columns of a table:
let xvm = document.getElementsByClassName("removedor");
let k = 0
let y = document.querySelectorAll('td')
let ya = document.querySelectorAll('td').length
let z = document.querySelectorAll('th')
let za = document.querySelectorAll('th').length
let restaurador = document.getElementsByClassName('restaurador');
for (let k = 0; k < za; k++) {
let xvm = document.getElementsByClassName("removedor");
let y = document.querySelectorAll('td')
let ya = document.querySelectorAll('td').length
let z = document.querySelectorAll('th')
let za = document.querySelectorAll('th').length
let restaurador = document.getElementsByClassName('restaurador');
document.getElementsByClassName("removedor")[k].addEventListener("click", function() {
z[k].style.display = "none";
y[k].style.display = "none";
})
}
The code works with only the first row when i click to delete the columns. I want it to delete the column that i clicked from all the rows from the table.
You can add a class to each delete button, then run a forEach loop over that nodelist and check for a click. When the click hits use the event.target and head up the nodelist to the nearest parent element to add a verification => e.target.closest('td') this will give you the table data element your button is residing within. Then you can insert a verification to make sure the user wishes to delete or not, getting the id of the row =>
td.insertAdjacentHTML('beforeend', ` <label class="checkLabel">Delete ${row}? <input type="checkbox" class="checkYes"></label>`);
A second event listener to check if the class we add into the DOM for the check is present in the DOM => checkYes.addEventListener('change', deleteRow); if this is not present we add the HTML that will delete the row.
checkYes.addEventListener('change', deleteRow);
The function to deleteRow:
function deleteRow(e){
e.target.closest('tr').remove();
}
I did not add a toggle for the delete button, but you could also add a toggle to the delete button that will hide the secondary verification if you hit the delete button again.
const del = document.querySelectorAll('.del');
function deleteRow(e) {
e.target.closest('tr').remove();
}
function checkDel(e) {
let td = e.target.closest('td');
let row = e.target.closest('tr').id;
if (!td.querySelector('.checkYes')) {
td.insertAdjacentHTML('beforeend', ` <label class="checkLabel">Delete ${row}? <input type="checkbox" class="checkYes"></label>`);
}
let checkYes = td.querySelector('.checkYes');
checkYes.addEventListener('change', deleteRow);
}
del.forEach(btn => {
btn.addEventListener('click', checkDel);
})
<table id="myTable">
<tr id="row_1">
<td>Row 1 Col 1</td>
<td>Row 1 Col 2</td>
<td>Row 1 Col 3</td>
<td>Row 1 Col 4</td>
<td><button class="del">Delete this row</button></td>
</tr>
<tr id="row_2">
<td>Row 2 Col 1</td>
<td>Row 2 Col 2</td>
<td>Row 2 Col 3</td>
<td>Row 2 Col 4</td>
<td><button class="del">Delete this row</button></td>
</tr>
<tr id="row_3">
<td>Row 3 Col 1</td>
<td>Row 3 Col 2</td>
<td>Row 3 Col 3</td>
<td>Row 3 Col 4</td>
<td><button class="del">Delete this row</button></td>
</tr>
</table>

Clickable table row linked to url

I am looking to see if there is a more updated solution to a similar problem here by following ECMAScript 6.
Suppose I have a table with a row as following:
<tbody>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
</tbody>
and a link contained in url. How do I make the entire row (not just the data cell) clickable leading to the page url, using Javascript? Thanks.
I'm not too sure what you mean by entire row(not just the data cell). Are you wanting to actually display the html code on the screen? Is that what you mean by entire row?
If you are just wanting the Row 1 Cell 1 as a hyperlink then this code below might help.
yourjavascriptpage.js or use the upper section of code below in yourphpfile.php as echo
"<div class='link'>Row 1 Cell 1</div>";
"<div class='link2'>Row 1 Cell 2</div>";
"<div class='link3'>Row 1 Cell 3</div>";
document.getElementById("link").innerHTML = "Row 1 Cell 1";
document.getElementById("link2").innerHTML = "Row 1 Cell 2";
document.getElementById("link3").innerHTML = "Row 1 Cell 3";
yourhtmlpage.html
<td><div id="link"></div></td>
<td><div id="link2"></div></td>
<td><div id="link3"></div></td>
or maybe you are looking for something like this ....
var link = "Row 1 Cell 1";
var link2 = "Row 1 Cell 2";
var link3 = "Row 1 Cell 3";
var result1 = link.link("https://www.gosomewhere.com");
var result2 = link2.link("https://www.gosomewhere.com");
var result3 = link3.link("https://www.gosomewhere.com");
Or here is a complete javascript solution I found online for you
https://www.robertcooper.me/table-row-links
similar the answer as above, I am not sure what you want?
I just revise the code here
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function(){
$(".table").on("click", "tr[role=\"button\"]", function (e) {
window.location = $(this).data("href");
});
});
</script>
<style>
[data-href] { cursor: pointer; }
</style>
<table class="table table-striped table-hover">
<tbody>
<tr role="button" data-href="http://127.0.0.1:8080/">
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
</tbody>
</table>
</head>
you should change the code data-href="" to any url you want

create a .row.cells line for length of <tr>

Hello I want to create a script that takes the amount of (tr) it finds then creates these 3 lines of code but changes the number in them based on the number it gets of (tr) here is an example:
I have a line of code that counts the table rows in the table (after I press a button) minus the table header (th):
var rowCount = $('#items-table tr').length - 1;
what I want to do is say for example the number I get is 3, I want to duplicate these 3 lines of code and change the variable and the number inside them.
Here are the 3 lines of code I want to duplicate:
table = document.getElementById("items-table");
var cell1 = table.rows[1].cells[0].innerHTML;
var cell2 = table.rows[1].cells[1].innerHTML;
var cell3 = table.rows[1].cells[2].innerHTML;
what I want to change is the var so I can define it later so if I got 3 this is what I would want the output to be:
var cell1 = table.rows[1].cells[0].innerHTML;
var cell2 = table.rows[1].cells[1].innerHTML;
var cell3 = table.rows[1].cells[2].innerHTML;
var cell4 = table.rows[2].cells[0].innerHTML;
var cell5 = table.rows[2].cells[1].innerHTML;
var cell6 = table.rows[2].cells[2].innerHTML;
var cell7 = table.rows[3].cells[0].innerHTML;
var cell8 = table.rows[3].cells[1].innerHTML;
var cell9 = table.rows[3].cells[2].innerHTML;
How would I go about doing this? I would also want to great a variable that could represent all the var cell(s) like this
tableData = [] tableData.append(var cell7 = etc..)
so then I could take the tableData and:
localStorage.setItem("tableData", tableData);
so then I could call this table data variable inside another html file.
I would also like to localStorage the variable lines themselves so I could call them individually as-well.
localStorage.setItem("item-name-1", cell1);
How would I got about doing this?
Important Note: At the start of my html page the table is empty. I then append the data using several inputs and an add button.
Any Help is appreciated Thank you.
Use a variable with an array:
var table, cell, i, r, noofrows;
table = document.getElementById("items-table");
noofrows = table.rows.length;
for (i = 0, r = 0, cell = []; r < noofrows; i++, r++) {
cell[i] = table.rows[r].cells[0].innerHTML;
cell[i+1] = table.rows[r].cells[1].innerHTML;
cell[i+2] = table.rows[r].cells[2].innerHTML;
}
Then the first cell will be assigned to the variable cell[0], the second will be cell[1], etc. For example, document.write(cell[0]) will write "Item" (from your previous question).
document.write(cell[1]) will write "Size".
document.write(cell[3]) will write the first cell of row 2.
You're looking for an array, in your case probably an array of arrays:
let cells = Array.prototype.map.call(document.getElementById("items-table").rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
Live Example:
let cells = Array.prototype.map.call(document.getElementById("items-table").rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
console.log("cells:", cells);
.as-console-wrapper {
max-height: 100% !important;
}
<table id="items-table">
<tbody>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 1</td>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td>Row 3 Cell 1</td>
<td>Row 3 Cell 2</td>
<td>Row 3 Cell 3</td>
</tr>
<tr>
<td>Row 4 Cell 1</td>
<td>Row 4 Cell 2</td>
<td>Row 4 Cell 3</td>
</tr>
</tbody>
</table>
The Array.prototype.map.call part lets us use Array's built-in map function on rows and cells even though they aren't arrays, but are array-like. Alternatively, you could actually turn them into arrays with Array.from:
let cells = Array.from(document.getElementById("items-table").rows).map(row => {
return Array.from(row.cells).map(cell => cell.innerHTML);
});
Live Example:
let cells = Array.from(document.getElementById("items-table").rows).map(row => {
return Array.from(row.cells).map(cell => cell.innerHTML);
});
console.log("cells:", cells);
.as-console-wrapper {
max-height: 100% !important;
}
<table id="items-table">
<tbody>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 1</td>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td>Row 3 Cell 1</td>
<td>Row 3 Cell 2</td>
<td>Row 3 Cell 3</td>
</tr>
<tr>
<td>Row 4 Cell 1</td>
<td>Row 4 Cell 2</td>
<td>Row 4 Cell 3</td>
</tr>
</tbody>
</table>
Storing that in local storage is simply a call to JSON.stringify:
localStorage.setItem("tableData", JSON.stringify(cells));
Restoring it from local storage:
var cells = JSON.parse(localStorage.getItem("tableData") || "[]");
(The || "[]" part provides a default — an empty array — for when there is no tableData stored.)

Selecting rows and colums of a table using jquery and update its content

I have a HTML table followed by a simple form which accepts the table row and column like below
<table border="1" style="width:100%">
<tr>
<td>Row 1 Col1</td>
<td>Row 1 Col2</td>
<td>Row 1 Col3</td>
<td>Row 1 Col4</td>
<td>Row 1 Col5</td>
<td>Row 1 Col6</td>
</tr>
<tr>
<td>Row 2 Col1</td>
<td>Row 2 Col2</td>
<td>Row 2 Col3</td>
<td>Row 2 Col4</td>
<td>Row 2 Col5</td>
<td>Row 2 Col6</td>
</tr>
<tr>
<td>Row 3 Col1</td>
<td>Row 3 Col2</td>
<td>Row 3 Col3</td>
<td>Row 3 Col4</td>
<td>Row 3 Col5</td>
<td>Row 3 Col6</td>
</tr>
</table>
<form>
<input type="text" placeholder="Row" value="row"/>
<input type="text" placeholder="Column" value="column"/>
<button id="submitButton" type="submit"> Submit </button>
</form>
Table row and column can vary and can have n number of rows and columns. What i would like to do is based on the user input (selecting rows and column and submitting it) i want to update the content of the user selected row and column to say "Hello". if user selects a column, row combination which is not available alert an error message. How could i do this in jquery.
Thanks in Advance.
$('#submitButton').click(
function(){
var numrow = $('#numrow').val();
var numcol = $('#numcol').val();
var enttotal = numrow * numcol;
var lenrow = $('.dataupdate tr').length;
var lencol = $('.dataupdate tr:first-child td').length;
var tcol = $('.dataupdate tr td').length;
if(numrow <= lenrow && numcol <= lencol && enttotal <= tcol){
$('.dataupdate tr:nth-child('+numrow+') td:nth-child('+numcol+')').html('Hello')
}
else { alert('there is no such column in this table'); }
});
this is working fiddle link
http://jsfiddle.net/6vj92vcp/
You can use like this,
$("#submitButton").click(function (e) {
e.preventDefault();
var r = parseInt($("#row").val()) - 1;
var c = parseInt($("#column").val()) - 1;
$("table").find("tr").eq(r).find("td").eq(c).text("hello");
});
Fiddle
It is an undex based approach. First you need to find the nth row using the .eq() selector. Since the index is starting from 0, you need to decrement the actual value by 1.
You can use .find() method to get all the child elements.
$(document).ready(function(){
$("#submitButton").click(function(){
var row = parseInt($("#rows").val())-1;
var col = parseInt($("#cows").val())-1;
var greeting = "hello";
if(isNaN(row)|| isNaN(col)) {
alert('Please enter a valid row and column number');
return false;
}
var x = $("table").find("tr").eq(row).find("td").eq(col);
if(x.length==0)
alert('Such a row and column not found ');
else if(x.text()==greeting)
alert("Already selected ");
else
x.text(greeting);
return false;
});
});
http://jsfiddle.net/tintucraju/fm0sL4s9/

Javascript getting the value of an input in a table [duplicate]

This question already has answers here:
How to retrieve value of input type in a dynamic table
(6 answers)
Closed 7 years ago.
I'm just wondering if it's possible to get the value of an html input in a table without naming each input separately and using getElementById directly onto the input so if I had the following table
<table id="table01">
<tr>
<td>row 0 cell 0</td>
<td>row 0 cell 1</td>
</tr>
<tr>
<td>row 1 cell 0</td>
<td>row 1 cell 1</td>
</tr>
</table>
I know in Javascript you can use the following to get the value of a specific cell in a specific row using the following
var lv_value = document.getElementById("table01").rows[0].cells[1].innerHTML;
console.log(lv_cont);
and this would give me the value I want which is "row 0 cell 1".
If I had a table like the following however
<table id="table01">
<tr>
<td>row 0 cell 0</td>
<td>row 0 cell 1</td>
<td><input type="text" class="tbl_input"></input></td>
</tr>
<tr>
<td>row 1 cell 0</td>
<td>row 1 cell 1</td>
<td><input type="text" class="tbl_input"></input></td>
</tr>
</table>
Is it then possible to do something along the lines of
<!-- this is obviously wrong -->
var lv_input = document.getElementById("table01").rows[0].cells[2].input.value;
console.log(lv_input);
to get the value of the input in the first row
You should do something like this:
var lv_input = document.getElementById("table01").rows[0].cells[2].firstChild.value;
console.log(lv_input);
or use the querySelector to find the input element
var lv_input = document.getElementById("table01").rows[0].cells[2].querySelector('input').value;
console.log(lv_input);

Categories

Resources