How to add table rows when button clicked: jquery - javascript

I have a template which contains two add buttons and two tables. When user clicks add button rows should append to the respective table.
Example:
<div class="reports">
<div class="panel">
<table class="A">
<thead>
<td>A</td>
<td>B</td>
<td>C</td>
</thead>
<tbody></tbody>
</table>
</div>
<button class="add" type="button">Add</button>
</div>
Am using same code for creating table and add button with different ids report.js is
$('.reports').on('click','.add',function(){
//do something
});
I want rows to be appended to the respective table.

Use append()
$('.reports').on('click','.add',function(){
$(this).closest('.reports').find('table').append('<tr/>');
});

Assuming you have different ids at parent divs
$('.reports').on('click','.add',function(){
$(this) //button that was clicked
.parent() //div around the button
.siblings(".A") //sibling element that has the table
.find("table tbody") //the table
.append(tableRow);

The vanilla Js approach:
var button = document.getElementsByClassName('add');
var table = document.getElementsByClassName('A');
button.addEventListener('click', function(){
var tr = document.createElement('tr');
table.appendChild(tr);
});

Related

Why only get tr of table at first time? [duplicate]

This question already has answers here:
How to append one jQuery element already in the DOM to another element?
(5 answers)
Closed 3 months ago.
I want get row of table 2 add to table 1, this is my js code:
$('#btnAdd').click(function () {
var table = $('#table1');
var tr =$("#table2 tr");
table.append(tr);
return false;
});
This is html code :
<div style="display: none;" id="rowitem">
<table id="table2">
<tr>
<td>No1</td>
<td>No2</td>
<td>No3</td>
</tr>
</table>
</div>
<div>
<table id="table1">
<tr>
<td>No1</td>
<td>No2</td>
<td>No3</td>
</tr>
</table>
<input id="btnAdd" type="button" value="+"/>
</div>
At first time, it get tr and add row ok.
But if i click add again, tr =undefined
Why can't get row of table, if click next time?
try
$('#btnAdd').click(function () {
var table = $('#table1');
var tr =$("#table2 tr").clone();
table.append(tr);
return false;
});
Instead of copying the tr's you are moving it
The issue is by appending, you are moving the whole tr element that causes the tr unavailable after first click. You should append the cloned table with .clone():
$('#btnAdd').click(function () {
var table = $('#table1');
var tr = $("#table2 tr").clone();
table.append(tr);
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="display: none;" id="rowitem">
<table id="table2">
<tr>
<td>No1</td>
<td>No2</td>
<td>No3</td>
</tr>
</table>
</div>
<div>
<table id="table1">
<tr>
<td>No1</td>
<td>No2</td>
<td>No3</td>
</tr>
</table>
<input id="btnAdd" type="button" value="+"/>
</div>

javascript get external table row on click

I have a button:
<button id="external-list-row">Test</button>
in which I would like to change with a row from an external table on click. The external table is structured like this;
<table id="table_id">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>Row 1</p>
</td>
</tr>
<tr>
<td>
<p>Row 2</p>
</td>
</tr>
<tr>
<td>
<p>Row 3</p>
</td>
</tr>
</tbody>
</table>
So my question is this; how can I replace "Test" in the button with the content of Row 1 with javascript?
As for the javascript, I'm not sure how I can get the content from row 1, and replace the button with it.
<script>
var rows = document.getElementById('table_id').getElementsByTagName("tr");
for (var i=0; i<rows.length; i++) {
$('#external-list-row').onclick = function() {
}};
</script>
Post comments:
I can access table data from other tables within the same html file, but I still don't know how to access data from tables in other html files. For example, if I try to access a videos liquid file from another liquid file, like photos, nothing happens when I press the button.
Fiddle of current code. It can replace the content of a list with the content of another, but the lists need to be on the same html file.
https://jsfiddle.net/hgnymydL/
Well, the first thing you should understand, is that a table element has a rows property, so getting the first row is trivial.
var table = document.getElementById("table_id");
var firstRow = table.rows[0];
From there, you can use textContent to get the text content of the row. I believe that's what you were looking for.
You can also select the first row of a table with a CSS selector like so:
var firstRow = document.querySelector("#table_id tbody tr");
$('#external-list-row').on('click', function() {
$(this).text($('#table_id tbody tr:first').text());
});
If you want to replace the button text with contents of the First Row ONLY then:
$('#external-list-row').html($('tr:first-child').html);
Of course you could wrap this in any event, so for example, on clicking the button:
$('#external-list-row').on('click', function() {
$(this).html($('tr:first-child').text());
});
BUT, based on the code you have given, I'm assuming you want to change the text after each click in which case you could do this:
var clickNumber = -1;
$('#external-list-row').on('click', function(event) {
clickNumber = clickNumber + 1;
//console.log('\n\nclickNUmber' + clickNumber);
$('tbody tr').each(function(index, el) {
//console.log('index: ' + index);
var block = $(el).find('td p');
if(index == clickNumber) {
//console.log('entered if')
//console.log(block.text());
//console.log('----clickNUmber' + clickNumber);
//console.log('index: ' + index);
//console.log(el);
$('#external-list-row').html(block.text());
}
});
});
jsFiddle: https://jsfiddle.net/zmb2b37t/
Hope that helps!
If you are wanting to replace the visible text "Test" in the button with the content of the cell clicked:
var tbl = document.getElementById('table_id');
var btn = document.getElementById('external-list-row');
tbl.onclick = function(ev){
var trgt = ev.target;
if(trgt.tagName === 'P' ||trgt.tagName === 'TD'){
btn.textContent = trgt.textContent;
}
};
Only one event handler is attached in this scenario.
Via event delegation we determine if it was a TD or P element that was clicked. If the rows are modified the function will still work.
Here is jquery code of do this
$('#table_id tr td').on('click', function(){
$('#external-list-row').html($(this).html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="external-list-row">Test</button>
<table id="table_id">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>Row 1</p>
</td>
</tr>
<tr>
<td>
<p>Row 2</p>
</td>
</tr>
<tr>
<td>
<p>Row 3</p>
</td>
</tr>
</tbody>
</table>

How to append td element in the same column of th element in a table?

I need to append data to a table dynamically from a JSON object.
After adding the titles as th elements, I am finding it difficult to add tr elements in the same column as the corresponding th element. Please help me.
{
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
}
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
</table>
Now, I need to add items in td tags in the columns same as their corresponding th elements. like:
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
<tr>
<td>Item1</td>
</tr>
<tr>
<td>Item2</td>
</tr>
<tr>
<td>Item3</td>
</tr>
</table>
How can I do this using jQuery? (My problem is bigger than this. I simplified it so that it can be understood. Thank you!)
Here you go, Press Run code snippet and check if this works for you.
var nodes = {
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
};
$(function(){
var th_elements = $('table').find('th'); // find <th> in HTML
th_elements.each(function(){ // Loop as much <th> found
var html = $.trim($(this).html()); // get HTML and compare with nodes key
$('table').append('<td>'+nodes[html]+'</td>'); // append data to table
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
</table>

How to get row id from row Index in table using JavaScript

Suppose this is my table:
<table>
<tr id="a">
<TD>a</TD>
</tr>
<tr id="b">
<TD>b</TD>
</tr>
</table>
How can I get row id using the row index from a table?
Above is just an example where id is static but in my case my id is dynamic, so I can't use
document.getElementById().
Assuming you have only one table on your page:
document.getElementsByTagName("tr")[index].id;
Preferably though, you'd give your table a id, though, and get your row like this:
<table id="tableId">
<tr id="a">
<td>a</td>
</tr>
<tr id="b">
<td>b</td>
</tr>
</table>
var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);
This way, you can be certain you don't get any interference, if you have multiple tables in your page.
"So, How can i get row id using row Index from a table"
You would select the table, and use the .rows property to get the row by index.
var table = document.getElementsByTagName("table")[0]; // first table
var secondRow = table.rows[1]; // second row
Then you just get the ID in the typical manner.
console.log(secondRow.id); // "b"
DEMO: http://jsfiddle.net/MErPk/
Answer has been edited
With CSS3 you can use the nth-child selctor. Here the example shows the rowIndex = 2
alert(document.querySelector("table tr:nth-child(2)").id);
In jQuery you can do this with
alert($("table tr:nth-child(2)").attr('id'));
The same syntax nth-child() can be used in CSS
<style>
tr:nth-child(2) {
color: red;
}
</style>

How to get row of element in cell by javascript/jquery?

I have a simple table like this
<table id="tempTable">
<tbody>
<tr id="row_01">
<td>
<button onclick="btnclick(this);" >Save Row</button>
</td>
</tr>
<tr id="row_02">
<td>
<button onclick="btnclick(this);" >Save Row</button>
</td>
</tr>
</tbody>
</table>
function btnclick(e) {
var currentRow = $(e).parent().parent();
alert(currentRow.id);
}
I want to determine which row where the button clicked was placed. So I use some jquery method in btnclick() as you see abow. But sometime I don't know how deep level the button was placed in row (), so Im looking for a way to get an ancestor by tag <tr> of a element.
Anybody help me, thanks?
Try this :
function btnclick(e) {
var currentRow = $(e).closest('tr');
alert(currentRow.id);
}
The closest() function will return the closest ancestor referenced by its selector. In this case the selector is simple a <tr> element.
Taken from the jQuery docs :
.closest( selector )
Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
A better method could be used if you change your HTML a little bit. If you placed the same class on each of your buttons.
Eg :
<td>
<button class="myBtnClass" >Save Row</button>
</td>
Then your jQuery would look like this :
$(".myBtnClass").on('click',function(){
var currentRow = $(this).closest('tr');
alert(currentRow.attr('id'));
});
This function will capture a click on any element with the .myBtnClass class.
The jQuery way is:
$('#tempTable').find('button').click(function() {
var currentRow = $(this).closest('tr');
});
how about using closest
function btnclick(e) {
var currentRow = $(e).closest('tr');
alert(currentRow.id);
}

Categories