jQuery appendTo ignoring last element - javascript

I'm trying to append a copy of an element to the bottom of the parent element. It seems to append everything above the last element within the parent. Live example on JSFiddle
var count = 1;
$("#addBtn").click(function(){
$('#trid1').clone().appendTo('table#exampleTable > tbody');
count++;
$('#trid1').last().prop('id', 'trid'+count);
$('#trid'+count+' > th').html(count);
});
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="exampleTable">
<thead>
<tr>
<th scope="col">c1</th>
</tr>
</thead>
<tbody>
<tr id="trid1" class="trclass">
<th scope="row">1</th>
</tr>
</tbody>
</table>
<button type="button" id="addBtn">Add</button>

I would change the id before appending the new element to the DOM.
Anyway I slightly refactored your code with that strategy in mind and better dealt with the current index every time you click the add button. The latest index gets saved in a data attribute in the table.
$("#addBtn").click(function(){
const latestIndex = $('#exampleTable').data('latest-index');
let i = latestIndex+1;
const newRow = $('#trid1').clone();
newRow.prop('id', `trid${i}`);
newRow.data('index', i);
newRow.text(i);
newRow.appendTo('table#exampleTable > tbody');
$('#exampleTable').data('latest-index', i);
});
button{
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="exampleTable" data-latest-index="1">
<thead>
<tr>
<th scope="col">Rows</th>
</tr>
</thead>
<tbody>
<tr id="trid1" class="trclass">
<th scope="row">1</th>
</tr>
</tbody>
</table>
<button type="button" id="addBtn">Add</button>

Related

How can I get only one column value from html table?

I have a html table that shows a list of users ID, Name and E-mail. When my user clicks in any row, I get the id number of that row and send to my backend. So, I did this:
//Making the table
var trs = document.getElementsByTagName('tr');
for (var i = 0; i < trs.length; i++) {
trs[i].onclick = clickHandler;
}
Function that handles the click:
function clickHandler(event) {
var numb = this.innerText.match(/\d/g);
numb = numb.join("");
window.location.replace("chooseParticipant.php?id="+numb);
}
Table Example:
<div id="table">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<td>7</td>
<td>Test User</td>
<td>testuser123#example.com</td>
</tbody>
</table>
</div>
What happens then? If an user have numbers in their e-mail, the "numb" variable gets these numbers too. I don't know how to filter only the id number. Did someone have any ideas?
You could assign a class to you tag.
Something like below:-
<td class="id">7</td>
And in the javascript code you could fetch all the elements with class "id".
And then perform your click handler on each one.
var trs = document.getElementsByClassName('id');
I hope this helps.
Try this code snippet which use data-* attribute
document.addEventListener('DOMContentLoaded', function(e) {
var trs = document.querySelectorAll('#table tbody tr');
var repeater = Array.prototype.slice;
repeater.call(trs).forEach(function(tr) {
tr.addEventListener('click', function(e) {
var data = tr.querySelector('td[data-id]').dataset;
console.log('id=', data.id);
});
});
});
tbody {
cursor: pointer;
}
<div id="table">
<table border="1" cellspacing="0" cellpadding="3">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="7">7</td>
<td>Test User 1</td>
<td>testuser1231#gmail.com</td>
</tr>
<tr>
<td data-id="8">8</td>
<td>Test User 2</td>
<td>testuser1232#gmail.com</td>
</tr>
<tr>
<td data-id="9">9</td>
<td>Test User 3</td>
<td>testuser1233#gmail.com</td>
</tr>
</tbody>
</table>
</div>

How can you target a child element of an iterated object in JavaScript?

In this instance I simply want to target tables that have a thead tag.
I trying to concatenate or search using JavaScript or jQuery whichever is quicker.
e.g thead = DT[i].children('thead');
function go() {
var i = 0,
DT = document.getElementsByClassName('DT');
for (i; i < DT.length; ++i) {
var x = DT[i];
if ($(x + ' thead').length) {
//do stuff to this table
}
}
}
<table class="DT" id="gv1">
<tbody>
<tr>
<th>th</th>
</tr>
<tr>
<td>td</td>
</tr>
</tbody>
</table>
<table class="DT" id="gv2">
<thead>
<tr>
<th>thead</th>
</tr>
</thead>
<tbody>
<tr>
<td>td</td>
</tr>
</tbody>
</table>
You don't need any loops, you can use jQuery's :has() selector to retrieve an element based on whether or not it contains a specified child, like this:
function go() {
$('.DT').has('thead').addClass('foo');
}
go();
.foo { border: 1px solid #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="DT" id="gv1">
<tbody>
<tr>
<th>th</th>
</tr>
<tr>
<td>td</td>
</tr>
</tbody>
</table>
<table class="DT" id="gv2">
<thead>
<tr>
<th>thead</th>
</tr>
</thead>
<tbody>
<tr>
<td>td</td>
</tr>
</tbody>
</table>
You can use querySelector to check if the nested thead exists.
if (x.querySelector("thead")) {
//do stuff to this table
}
Just so you know, you'd do this to accomplish what you were trying originally:
if ($(x).find("thead").length) {
//do stuff to this table
}
This is just to show how you can perform DOM selection from a given context.

How to clone a whole table in Javascript?

I tried to use cloneNode mentionned here Copy the content of one table into another but Chrome says cloneNode is not a function
https://jsfiddle.net/4wczdykc/1/
<table>
<thead>
<tr>
<th scope="col" colspan="1">TABLE TO CLONE</th>
</tr>
<tr>
<th>Column</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
script:
myTable = document.getElementsByTagName("Table")[0];
myClone = myTable.cloneNode(true);
document.body.appendChild(myClone);
The getElementsByTagName() method accesses all elements with the specified tagname.So you have to select the first element of the NodeList. So passed [0] to select it.
myTable = document.getElementsByTagName("table")[0];
myClone = myTable.cloneNode(true);
document.body.appendChild(myClone);
WORKING FIDDLE

How to copy the contents of one row in a table to another table and add the identical ones

var Sell_Button = document.getElementById('sellbtn'),
secondTable = document.getElementById("secondTableBody");
Sell_Button.addEventListener('click', function() {
var Row = secondTable.insertRow();
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[2].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
//checks to see if the secondTable has a row containing the same name
for (var f = 0; f < secondTable.rows.length; f += 1) {
//adds only the sold amount if the second table has a row with the same name
//error
if (secondTable.rows[f].cells[0].innerText === this.parentNode.parentNode.cells[0].innerText) {
secondTable.rows[f].cells[1].innerHTML = +this.parentNode.parentNode.cells[2].innerHTML;
//deletes an extra row that is added at the bottom
if (secondTable.rows.length > 1) {
secondTable.deleteRow(secondTable.rows.length - 1);
}
//if nothing matched then a new row is added
} else {
secondTable.insertRow();
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[2].innerHTML;
}
}
}
}
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Ok, this example isn't exactly what i'm working on but it's very similar. The only difference is that in mine the rows and buttons are dynamically added by the user and he inserts the details. What I want is that when i press on the button of each row (sell) the details (Item and Sold only) are copied into a row in the second table and checks if the same item exists in this second table if so then it adds the amount of sold of both items in one row. For instance I press on the first row button the Apples it copies the listed above details to the second table in a row and then when i click on the button of the second row (Apples also) it only adds the sold amount up and doesn't add a second apples row because an apples row already exists in the second table but when i click on the oranges button it makes a new row because the oranges row doesn't exist. So how do I do this in JavaScript? i hope i was thorough and made any sense. I have no idea why the code isn't working here but i hope you get the point. This code works perfectly just as i want it to until for some reason i get this error: Cannot read property 'innerText' of undefined when i press the buttons approx. 6-7 times targeting the if statement where i commented error.
This sets a click handler to all buttons. If the row doesn't exist in the second table it's created. It sets a data-type referring to the item. When somebody clicks the sell button again and there is a row containing the data-type the row is updated instead of created. All in plain JavaScript.
var Sell_Button = document.querySelectorAll('.sellbtn'),
secondTable = document.getElementById("secondTableBody");
Array.prototype.slice.call(Sell_Button).forEach(function(element){
element.addEventListener('click', function(e) {
//since the button is an element without children use e.
var clickedElement = e.target;
var parentRow = clickedElement.parentNode.parentNode;
//check if second table has a row with data-type
var rowWithData = secondTable.querySelector("[data-type='"+parentRow.cells[0].childNodes[0].nodeValue+"']");
if (rowWithData)
{
rowWithData.cells[1].innerHTML = parseInt(rowWithData.cells[1].childNodes[0].nodeValue) + parseInt(parentRow.cells[2].childNodes[0].nodeValue);
}
else
{
var Row = secondTable.insertRow();
Row.setAttribute("data-type", parentRow.cells[0].childNodes[0].nodeValue);
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = parentRow.cells[0].childNodes[0].nodeValue;
Row.cells[1].innerHTML = parentRow.cells[2].childNodes[0].nodeValue;
}
});
});
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Do you mean something like:
$(document).on("click", "#firstTable tr button", function(b) {
b = $(this).closest("tr");
var d = $.trim(b.find("td:first").text());
b = parseFloat($.trim(b.find("td:nth-child(3)").text()));
var a = $("#secondTable"),
c = a.find("tr").filter(function(a) {
return $.trim($(this).find("td:first").text()) == d
});
c.length ? (a = c.find("td:nth-child(2)"), c = parseFloat($.trim(a.text())), a.text(b + c)) : (a = $("<tr />").appendTo(a), $("<td />", {
text: d
}).appendTo(a), $("<td />", {
text: b
}).appendTo(a))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<tr>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</tr>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td><button>Sell</button></td>
</tr>
</tbody>
</table>
</div>
<br />
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<tr>
<th>Item</th>
<th>Sold</th>
</tr>
</thead>
<tbody id="secondTableBody"></tbody>
</table>
</div>

Getting TD value from TR

I'm new to Javascript and I'm having trouble to get the value from a <td>.
Here is some code to illustrate the problem:
<div id="lista_ativo">
<table class="tabela-basica" width="100%" cellpadding="0px" cellspacing="0px">
<thead>
<tr>
<th width="35px">ID</th>
<th width="200px">Cliente</th>
<th width="200px">Nome</th>
<th width="35px">OAB</th>
<th width="50px">Estado</th>
</tr>
</thead>
<tbody>
<tr class="{classe_row}">
<td data-id="{andamentos_ativos.clienteid}">{andamentos_ativos.clienteid}</td>
<td>{andamentos_ativos.cliente}</td>
<td>{andamentos_ativos.nome}</td>
<td>{andamentos_ativos.oab} / {andamentos_ativos.oab_uf}</td>
<td>{andamentos_ativos.estados}</td>
</tr>
</tbody>
</table>
</div>
My Javascript:
$("#lista_ativo").delegate("tr", "click", function() {
var idbcorporativo = $(this).attr("data-id");
console.log(idbcorporativo);
});
I need the data-id from the first <td>.
You need to go from the tr to the th.
And then reference to the first child beginning by 0.
var idbcorporativo = $(this).children()[0].attr("data-id");
you can try using getAttribute
document.getElementsByTagName("td")[0].getAttribute("data-id");
or with jQuery you can modify your code to
$("#lista_ativo").delegate("tbody tr", "click", function() {
var idbcorporativo = $(this).children().attr("data-id");
console.log(idbcorporativo);
});
here's the example fiddle

Categories

Resources