How to get current td value from table onclick? - javascript

I want value of first td onclick whenever i click on any of the table row. I am using jquery below code to create table rows dynamic.
This data is javascript array of key value pairs.
$(document).ready(function(){
$.each(Data, function(key, value) {
$('#idforappend').append('<tr class="tr_use"><td>'+key+'</td><td>'+key+'</td><td>'+value+'</td></tr>');
});
});
Now when i click on any row i want first td value only that row. How can we do that please help.

I have created a dynamic table using jS. when clicking on the row it will console 1st TD value only.
jQuery('document').ready(function(){
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);
jQuery('tr').on('click', function(){
console.log(jQuery(this).find('td').first().text());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is the solution thanks.
$(document).ready(function(){
// code to read selected table row cell data (values).
$(".btnSelect").on('click',function(){
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").html();
});
});

Just add the same onClick handler on each row when you are creating your table.
$(document).ready(function(){
$.each(Data, function(key, value) {
$('#idforappend').append('<tr class="tr_use" onClick="handle(event)"><td>'+key+'</td><td>'+key+'</td><td>'+value+'</td></tr>');
});
});
Your resultant table should be something similar to the below table
<table>
<tr onClick="handle(event)">
<td>key1</td>
<td>value1</td>
</tr>
<tr onClick="handle(event)">
<td>key2</td>
<td>value2</td>
</tr>
</table>
Your event handler
function handle(event){
console.log(event.currentTarget.children[0].textContent);
}

Related

Creating text element in seperate cells across columns

What I am trying to do is on button press I will add 4 text elements, each text element in its own cell; beneath its corresponding column. Eg. "Name" column will have the name of the product beneath it. Refer to picture attached below.
My problem is - On button press my 4 elements are created but only one cell is created and it has all 4 of my elements in it. If someone could help me find the solution that would be amazing!
Relevant code attached below.
<div id="inventory">
<!--Here is where we shall store our data-->
<table class="table">
<tr class="head-row">
<th class="table-head">Name</th>
<th class="table-head">Price</th>
<th class="table-head">ID</th>
<th class="table-head">Quantity</th>
</tr>
<div>
Javascript:
//Items
let items = [
["chips",25,3163,1],
["Pork", 25 , 316 , 1],
["Crackers",5,400,1]
];
addButton.addEventListener('click', addItem);
function addItem(){
let table = document.querySelector(".table");
let row = document.createElement('tr');
row.classList.add("row");
let cell = document.createElement('td');
cell.classList.add('item-properties')
//Create our table item
items[1].forEach(itemProperty =>{
let textNode = document.createTextNode(itemProperty);
cell.appendChild(textNode);
row.appendChild(cell);
});
table.appendChild(row);
}
You need a td element for each value.
//Items
let items = [
["chips", 25, 3163, 1],
["Pork", 25, 316, 1],
["Crackers", 5, 400, 1]
];
document.getElementById('add').addEventListener('click', addItem);
function addItem() {
let table = document.querySelector(".table");
let row = document.createElement('tr');
row.classList.add("row");
let cell = document.createElement('td');
cell.classList.add('item-properties')
//Create our table item
items[1].forEach(itemProperty => {
let td = document.createElement('td');
let textNode = document.createTextNode(itemProperty);
td.appendChild(textNode);
row.appendChild(td);
});
table.appendChild(row);
}
<button id="add">Add</button>
<div id="inventory">
<!--Here is where we shall store our data-->
<table class="table">
<tr class="head-row">
<th class="table-head">Name</th>
<th class="table-head">Price</th>
<th class="table-head">ID</th>
<th class="table-head">Quantity</th>
</tr>
</table>
</div>
I got the problem all solved!
Just had to create the cell variable inside the forEach loop, so now it will loop through and create a cell each time- then add my textNode to that cell. If anyone has any pointers or alternate solutions more than happy to hear!
function addItem(){
let table = document.querySelector(".table");
let row = document.createElement('tr');
row.classList.add("row");
//Create our table item
items[1].forEach(itemProperty =>{
let textNode = document.createTextNode(itemProperty);
cell = document.createElement('td'); //ADDED THIS
cell.appendChild(textNode);
row.appendChild(cell);
console.log(itemProperty);
});
table.appendChild(row);
}

Javascript inserting data into cell with index and data

This seems very simple but I just can't get my head around it. I am trying to insert data I get back and replace the cell contents at the specified cell index. I am getting the data (Kevin) and index (0) back from the function call's input parameters. But I'm just not able to insert this data into the desired cell. I have tried insertCell function, but this won't replace the contents, it'll just keep appending new cells.
My console.logs report the correct index and data, I've tried inserting/replacing the content of the cell like this: td[index].innerHTML = data but this gives an error, apparently td[index] returns a object HTMLTableCellElement, so i can't do it this way.
HTML:
<table>
...
<tbody>
<tr id="data-row-body">
<td></td> //need to insert here
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Javscript:
function exeAPI(api, key, index, callback) {
$.ajax({
url:"../lib/getData.php",
type: "POST",
data: {
name: name,
api: api
},
dataType: "text",
success:function(result){
console.log(result);
if(result){
try {
var jsonText = result.substr(result.indexOf('{'));
console.log("this is the jsontext: " + jsonText);
var jsonObj = JSON.parse(jsonText);
callback(jsonObj.response.result[key], index);
} catch(e) {
console.log(e);
alert("Error getting rack data!");
}
}
}
});
//getting back "Kevin" and "0" as parameters to insert here
function exeAPIcallback(data, index){
var td = $('#data-table tbody td');
var tr = $('#data-table tbody tr');
var row = document.getElementById("data-row-body");
console.log("This is the cell index: " + th[index].innerHTML + " ,index: " + th[index]);
console.log("This is the cell index: " + td[index]);
td[index].innerHTML = data; // this doesn't work
}
function popupParamChecker(){
exeAPI("getData.php", "Kevin", 0, exeAPIcallback);
$("#dialog-params").dialog({
resizable: false,
width: 1000,
modal: true,
draggable: false,
buttons: {
Confirm: function() {
$( this ).dialog( "close" );
}
}
});
}
Is there an easier way of doing this?
The count of row may be many, so I added one param for your APICallback.
Below is the codes:
1. First select our all rows under the table by $('table tbody tr')
2. use .eq(index) to get the specific row
3. .find() all tds then get the specific cell to change the text.
function exeAPIcallback1(data, row, col){
let td = $('table tbody tr').eq(row).find('td').eq(col);
td.text(td.text()+data)
}
function exeAPIcallback2(data, row, col){
$('table tbody tr').eq(row).find('td').eq(col).text(data);
}
table td{
width:10px;
height:10px;
border:1px;
background-color:yellow;
}
table td:nth-child(even){
background-color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="exeAPIcallback1('test',0,0)"> Test Insert</button>
<button onclick="exeAPIcallback2('test',0,0)"> Test Replace</button>
<table>
<tbody>
<tr id="data-row-body">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Use the following function to add content to a table cell.
function add_content_to_cell(table_selector, row_number, cell_number, content) {
$(table_selector).find('tr')
.eq(row_number-1).find('td').eq(cell_number-1)
.append(content);
}
Simply choose the table id, the row number, the cell number and the content you wish to add.
Usage:
add_content_to_cell('#my_table', 2, 5, "I am some content")
Result:
With jQuery:
$('#data-row-body').find('td').eq(index).text(data); /* strips down html, if any */
OR
$('#data-row-body').find('td').eq(index).html(data); /* with html tags */
See if this works, with your current snippet
change
var td = $('#data-table tbody td');
to
var td = $('#data-row-body').children('td');
$(td[index]).html(data);
here, assuming that index is always within the bounds of

Show a table (number of rows variable) on a div after click button? Works until some point

(This is my first question here and I am new to programming)
I am stuck on a problem and I tried to take something from here:
http://jsfiddle.net/4pEJB/
Dynamically generated table - using an array to fill in TD values
The function I created receive two vectors and creates a table with 2 columns, one for each vector, and lines = vector.length.
The function works fine, it seems to create the table as I need, but it doesn't show the table created on the browser screen after button click. By using some 'alert()' on the for loops I was able to verify that it uses the correct data.
In fact, when the button is clicked, it calls another function that processes some data and passes two vectors on this function I am showing here, but this part works well.
Here is the HTML part:
<div class="tableDiv">
<input type="button" onclick="createtable([1,3,5,7,9],[2,4,6,8,10])" value="Show data">
</div>
And here is the JavaScript part:
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
tableDiv.appendChild(table);
}
When the function finishes the table feed, it stops on tableDiv.appendChild(table);
Any advice or suggestions will be greatly appreciated! (I speak portuguese, I am sorry for some errors)
EDIT: it's possible to avoid the increment on the number of table rows that occurs every time we click the button (the solution provided generates one new table under the previous table). To solve this, I just added this line on the beggining of the function code (need to put the button outside the div and let the div empty, otherwise it will hide the button):
document.getElementById("tableDiv").innerHTML = "";
you are capturing by id, but you set up a class.chang it to id
<div id="tableDiv">
and append the tableBody into table.You're populating the table body with rows, but never appended the body into the table element.
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
table.appendChild(tableBody) // append tableBody into the table element
tableDiv.appendChild(table);
}
<div id="tableDiv">
<input type="button" onclick="createtable([1,3,5,7,9],[2,4,6,8,10])" value="Show data">
</div>
You try to append the var table to the tableDiv but the var table is stil empty.
Before append the tableBody to the var table and it will work.
Use id instead of class in your HTML Markup
<div id="tableDiv">
and then use the following code.
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
tableDiv.appendChild(table);
}
First you are accessing the div using id whereas the node is defined with a class.
Secondly, you have to append the body to the table node first, and then append the table to the div selected.
Try this code snippet to move on.

jQuery table loop?

I'm trying to run through a table and change each cell based on the row. Table example:
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
Function example (in script under body):
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
$(document).load(myFunction);
The example shown is non-specific version of the actual function I'm trying to run.
To be clear, I have linked to the jQuery 2.1 CDN, so the page should be able to read jQuery.
Console shows no errors, but still does not run appear to run the function. Checking the tested row in the console shows no change to the html in the div. Any advice for this?
When I run it I get an error on r.find() because .find() is a jQuery function and needs to be called on a jQuery object, which r is not. Simply wrapping it in a $() works.
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
https://jsfiddle.net/k50o8eha/1/
You may need to do asomething similar to the c.getChild();
Here's a simplified version :
$("#myTable tr").each(function(i, r){
if(i==1)
{
$(this).find('td').each(function()
{
$(this).find("div").html("html here");
});
}
});
Example : https://jsfiddle.net/DinoMyte/4dyph8jh/11/
Can you give this a try...
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
});
or shorthand...
$(function() {
});
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = $(c).children('div');
square.text('html here');
});
}
});
});
table{
background-color: #eee;
width: 300px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
This works, you can try this
JSBIN
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i){
if(i==1){//to edit second row, for example
$(this).find('td').each(function(j){
$(this).find('div').html('html here');
});
}
});
}
$(document).ready(myFunction);
first the "id" should be unique to an element... but ok, this should do the trick:
$(document).ready(function(){
$("#myTable>tr:odd").children("div").text('html here');
});
If you want to put html code in the div, change text for html. if you want to specify the row then:
$(document).ready(function(){
myRow = //set its value...
$("#myTable>tr").each(function(idx, element){
if(idx == myRow){
element.children("div").text('html here');
}
}, myRow);
});

How can I dynamically create (or fake) a <th> cell using Javascript

I am using Javascript to dynamically create a table, and want to make a header-style cell at the beginning of each row. So my question is how I can do this, seeing as insertCell creates only a normal <td> element and not a <th>.
Some things I've tried (via the Tryit editor at w3schools; I have no reason to suspect that any other usage will behave differently) and didn't work:
I've seen a suggestion to create the <th> element independently and then add it to the <tr> element as a child. When I do this, however, it is not added as a table cell, i.e. it is not affected by the table border, does not count toward the array of cells (i.e. if you do insertCell(1), it inserts after the first cell not counting the <th>), and does not get the special bold/center format for a <th> cell.
I've attempted to use insertCell to make a dummy cell and then replaceChild with an independently created cell; this had the same result as above.
I've tried to make a <td> cell via insertCell and simply bold and center it manually, but myCell.style.fontWeight="bold" and myCell.align="center" don't seem to work (they just end the function, as bad commands do in JavaScript), and likewise trying to use CSS doesn't work. So maybe I just have bad syntax or something, but I've got no clue what to do. Any help would be appreciated.
Attempt 1:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to insert new cell(s) at the end of the table row.</p>
<table border="1">
<th>1</th>
<td>2</td>
</tr>
<tr id="myRow">
</tr>
<tr>
</table><br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var newRow = document.getElementById("myRow");
var header=document.createElement("th").appendChild(document.createTextNode("a"));
newRow.appendChild(header);
var enablesLoc=newRow.insertCell(0).appendChild(document.createTextNode("b"));
}
</script>
</body>
</html>
Result: "1" is bolded with a border, "2" and "b" are unbolded with a border (as they should be), "a" is unbolded with no border.
Attempt 2:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to insert new cell(s) at the end of the table row.</p>
<table border="1">
<th>1</th>
<td>2</td>
</tr>
<tr id="myRow">
</tr>
<tr>
</table><br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var newRow = document.getElementById("myRow");
var header=newRow.insertCell(0).appendChild(document.createTextNode("a"));
header.style.fontWeight="bold";
var enablesLoc=newRow.insertCell(1).appendChild(document.createTextNode("b"));
}
</script>
</body>
</html>
Result: The button adds cell "a" unbolded but not cell "b".
The following code shows everything that should get you going:
function addTable(){
var table = document.createElement("table");
var tr = document.createElement("tr");
var th = document.createElement("th");
var td = document.createElement("td");
td.innerText = "im a td";
th.innerText = "im a th";
tr.appendChild(th);
tr.appendChild(td);
table.appendChild(tr);
var out = document.getElementById("out");
out.appendChild(table);
}
You have to call the function and an div with id out <div id=out>...</div> must be in the document. Disclaimer: i only tested this code in chrome
Update to address your points
You wrote I've seen a suggestion to create the <th> element independently and then add it to the <tr> element as a child. When I do this
it is not added as a table cell what do you mean by that and what command are you using,
is not affected by the table border the reason could be because it contains not text,
does not count toward the array of cells (i.e. if you do insertCell(1) i do not understand this either. According to the specs on insertCell it insert an empty td and returns a reference. So insertCell has no array, If you try var table = document.getElementById("myTable") and then table.rows[0].cells.length it returns the number of cells including the th-cell.
it inserts after the first cell not counting the th according on my tests at least in chrome this is not the case; it depends on how you call the method: table.rows[1].insertCell(-1); adds a cell at the second row (zero based array) at the end and table.rows[2].insertCell(1); adds in the third row a cell on position 2 (again zero based) if you use table.rows[3].insertCell(0); the cell is inserted into the 4th. row at the beginning,
and does not get the special bold/center format for a th cell this was not the case for me as well
Disclaimer: i only tested this code in chrome
The html
<button onclick="addRow()">add rows</button><br />
<button onclick="addColumn()">add column</button>
<table border="1" id="myTable">
<tr>
<th>1</th>
<td>2</td>
</tr>
</table>
And the javascript
function addRow()
{
var table = document.getElementById("myTable");
var tr = document.createElement("tr");
var th = document.createElement("th");
var td = document.createElement("td");
td.innerText = "im a td";
th.innerText = "im a th";
tr.appendChild(th);
tr.appendChild(td);
table.appendChild(tr);
}
function addColumn(){
var table = document.getElementById("myTable");
var rows = table.rows;
console.log("rows", rows);
for (var i = 0; i < rows.length; ++i) {
// td = rows[i].cells;
var td = document.createElement("td");
td.innerText = i;
rows[i].appendChild(td);
}
}
Based on DOM Level 2 HTML you can not use insertCell since it Insert[s] an empty TD cell into this row. But you want to add a th
According to DOM Level 3 Core you can use appendChild since it adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.
So therefore you have to create the elements in the right order: create the row, add the first cell as th then add other cells as td by using append child.
You may take a look at a demo of the above code
The .appendChild() method returns the element being appended. Which means on this line:
var header=document.createElement("th").appendChild(document.createTextNode("a"));
...your header variable is actually the text node, not the th element - so then newRow.appendChild(header); appends just the text node to the row, not the new th.
Try something like this instead:
var newRow = document.getElementById("myRow");
var header = document.createElement("th");
header.appendChild(document.createTextNode("a"));
newRow.appendChild(header);
Demo: http://jsfiddle.net/PtzRL/
Note that if you actually want to append new rows then your newRow variable should not be getting a reference to an existing row in the table, you should give an id to the table:
<table id="myTable">
...and then create a new row and add that to the table:
var table = document.getElementById("myTable");
var newRow = document.createElement("tr");
table.appendChild(newRow);
Demo: http://jsfiddle.net/PtzRL/1/
(Note also that the starting html you show has an error: you're missing the first <tr> just after the <table> tag, and you have an extra <tr> just before the closing </table> tag.)
Is this what you were trying to do?
function myFunction = function() {
var newRow, newHeader, newCell;
newRow = document.getElementById("myRow");
newHeader = document.createElement("th");
newHeader.innerText = "a";
newRow.appendChild(newHeader);
newCell = document.createElement("td");
newCell.innerText = "b";
newRow.appendChild(newCell);
}
If you want the button to add new rows rather than filling in a blank row you put there already, try something like this:
HTML:
<body>
<table id="myTable" border="1">
<tr>
<th>1</th>
<td>2</td>
</tr>
</table>
<button onclick="myFunction()">Try it</button>
</body>
JavaScript:
function myFunction = function() {
var myTable, newRow, newHeader, newCell;
myTable = document.getElementById("myTable");
newRow = document.createElement("tr");
newHeader = document.createElement("th");
newHeader.innerText = "a";
newRow.appendChild(newHeader);
newCell = document.createElement("td");
newCell.innerText = "b";
newRow.appendChild(newCell);
myTable.appendChild(newRow);
}
The function need to altered like this I believe...
function myFunction()
{
var newRow = document.getElementById("myRow");
var header=document.createElement("th");
header.appendChild(document.createTextNode("a"));
newRow.appendChild(header);
var enablesLoc=newRow.insertCell(0);
enables.appendChild(document.createTextNode("b"));
}

Categories

Resources