I click on a button which has a class 'return' and I want to get an id of the card. Here is a peace of code.
$('.return').on('click', () => {
let a = $('.return').siblings();
console.log(a);
})
for (let card of cards) {
table += `
<tr>
<th scope="row">${card._id}</th>
<td>${card._visitor}</td>
<td>${card._bookName}</td>
<td>${card._borrowDate}</td>
<td>${card._returnDate==='not fetched'?'' + '
<button class="return"></button>':card._returnDate}
</td>
You can do it like this:
let a = $(this).parent().prevAll("th").text();
$(this) <- refers to the button that was clicked.
.parent() <- to access the td
.prevAll("th") <- to find the th that comes before you td
.text() <- to get the text aka ${card._id}
Problem is that your button is not the sibling of your th
Demo
$('.return').on('click', function() {
let a = $(this).parent().prevAll("th").text();
console.log(a);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th scope="row">${card._id}</th>
<td>${card._visitor}</td>
<td>${card._bookName}</td>
<td>${card._borrowDate}</td>
<td>${card._returnDate==='not fetched'?'' + '
<button class="return"></button>':card._returnDate}
</td>
</tr>
</table>
One option is to add the id to the button
<button class="return" data-id="${card._id}"..
then you can access that id without needing to traverse.
Note you're also using ()=> in the click event, so you won't be able to use this to reference the button. Change to function() to get this, giving:
$('.return').on('click', function() {
let id = $(this).data("id");
console.log(id);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th scope="row">1</th>
<td><button class="return" data-id="1">return</button>
</td>
</tr>
<tr>
<th scope="row">2</th>
<td><button class="return" data-id="2">return</button>
</td>
</tr>
</tbody>
<tr>
<th scope="row">752</th>
<td><button class="return" data-id="752">return</button>
</td>
</tr>
</table>
You can bypass jquery and use your script when adding cards to attach an onclick method to your button and retrieve the card id
const cards = [{
_id: 1,
_returnDate: "not fetched"
},
{
_id: 2,
_returnDate: "not fetched"
}
]
const table = document.querySelector("table")
for (let card of cards) {
table.innerHTML += ` <tr>
<th scope="row">${card._id}</th>
<td> <button class="return" onclick="buttonClick(${card._id});">Click Me</button></td>
</tr>`
}
function buttonClick(cardId) {
console.log("card id:", cardId)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
</table>
Related
I made a table to show some items and i want it to be cleared once i press the clear button.
Now the main problem is that my tr that i want to remove does'nt take tbody as its parent.
Here's my html:
<table>
<tbody id="stuffCarrier"></tbody>
</table>
and here's my javascript to remove the items:
document.getElementById("clearList").onclick = function () {
Array.from(document.getElementsByClassName("removeds")).forEach((e, i, arr) => {
document.getElementById("stuffCarrier").removeChild(e);
console.log(i, e, e.parentElement, arr);
});
localStorage.removeItem("CarriedStuff");
And here's my javascript how i added the items:
const stuffCarrier = document.getElementById("stuffCarrier");
stuffCarrier.innerHTML = `<tr>
<th class="stuffs">Quantity</th>
<th class="stuffs" style="color:red">Stuff</th>
<th class="stuffs" style="color:chartreuse">Cost</th>
</tr>
`;
showStuff.forEach(e => {
stuffCarrier.innerHTML += `<tr class="stuffs removeds">
<td>${e[2]}</td>
<td style="color:blue">${e[0]}</td>
<td style="color:white">${e[1] * e[2]}</td>
</tr>
`;
});
Array.from(document.getElementsByClassName("removeds")).forEach(d=>d.remove())
First try to add tr as childElement of stuffCarrier like this:
const stuffCarrier = document.getElementById("stuffCarrier");
childElement = `<tr>
<th class="stuffs">Quantity</th>
<th class="stuffs" style="color:red">Stuff</th>
<th class="stuffs" style="color:chartreuse">Cost</th>
</tr>
`;
stuffCarrier.appendChild(childElement);
Even within the for loop. Then I think you will be able to remove tr as removeChild().
Or you can directly remove all the selected elements like this:
Array.from(document.getElementsByClassName("removeds")).forEach(d=>d.remove()) without using removeChild() method.
I hope it helps.
you need a closing function bracket before the localstorage line, but other than that it works??
<input id='clearList' value='clear' type='button' />
<table>
<tbody id="stuffCarrier"></tbody>
</table>
<script>
var showStuff=[
[1,2,3],[4,5,6]
]
const stuffCarrier = document.getElementById("stuffCarrier");
stuffCarrier.innerHTML = `
<tr>
<th class="stuffs">Quantity</th>
<th class="stuffs" style="color:red">Stuff</th>
<th class="stuffs" style="color:chartreuse">Cost</th>
</tr>
`;
showStuff.forEach(e => {
stuffCarrier.innerHTML += `
<tr class="stuffs removeds">
<td>${e[2]}</td>
<td style="color:blue">${e[0]}</td>
<td style="color:cyan">${e[1] * e[2]}</td>
</tr>
`;
});
document.getElementById("clearList").onclick = function () {
var nl=document.getElementsByClassName("removeds");
Array.from(nl).forEach((e, i, arr) => {
document.getElementById("stuffCarrier").removeChild(e);
console.log(i, e, e.parentElement, arr);
});
}
</script>
description cells will starts as hide. The row that I click, will show the description and if i click another row will the current row description and hide the other description
var getTable = document.querySelector("tbody");
var cells = getTable.getElementsByTagName("td");
for (let item of document.getElementsByClassName("desc")) {
item.style.display = "none";
}
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function () {
var selectedRow =
getTable.getElementsByTagName("tr")[this.parentNode.rowIndex];
if (!this.parentNode.rowIndex) {
$(selectedRow).find(".desc").css("display", "none");
} else {
$(selectedRow).find(".desc").css("display", "block");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblInventory">
<thead>
<tr>
<th>UPC</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>987456</td>
<td>Product Blanks</td>
<td class="desc">Unfinished template for parts 1000222 to 1000299</td>
</tr>
<tr>
<td>654123</td>
<td>Threaded Rods</td>
<td class="desc">Rods threaded at both ends for Support Brackets</td>
</tr>
</tbody>
</table>
Try this in vanilla:
document.querySelector('#tblInventory').addEventListener('click', (e) =>
{
// Hide other descriptions
document.querySelectorAll('#tblInventory td.desc span').forEach(span => {
span.style.display = 'none';
});
// Show clicked row description
if (e.target.tagName === 'TD') {
e.target.parentNode.querySelector('td.desc span').style.display = 'inline';
}
});
#tblInventory td.desc span {
display: none
}
<table id="tblInventory">
<thead>
<tr>
<th>UPC</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>987456</td>
<td>Product Blanks</td>
<td class="desc"><span>Unfinished template for parts 1000222 to 1000299</span></td>
</tr>
<tr>
<td>654123</td>
<td>Threaded Rods</td>
<td class="desc"><span>Rods threaded at both ends for Support Brackets</span></td>
</tr>
</tbody>
</table>
Or with jQuery:
$('#tblInventory').on('click', 'td', (e) => {
// Hide other descriptions
$('#tblInventory td.desc span').hide();
// Show clicked row description
$(e.target).closest('tr').find('td.desc span').show();
});
#tblInventory td.desc span {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<table id="tblInventory">
<thead>
<tr>
<th>UPC</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>987456</td>
<td>Product Blanks</td>
<td class="desc"><span>Unfinished template for parts 1000222 to 1000299</span></td>
</tr>
<tr>
<td>654123</td>
<td>Threaded Rods</td>
<td class="desc"><span>Rods threaded at both ends for Support Brackets</span></td>
</tr>
</tbody>
</table>
Using span is a suggestion, but you can fix the selectors to show/hide the td elements directly as well;
If you don't want to hide previous clicked descriptions, just remove the related code.
I have created HTML markup using Javascript now I want to remove that element when clicked, but its not working
if (tBody) {
return (
`<tr class="tr1">
<th class="th1"> Category Name </th>
<th class="th1">Delete </th>
</tr>` +
getdata.data
.map(function (wizard) {
return `<tr class="td1"> <td class=".th1"> ${wizard.categoryName}</td>
<td class="td1"><a class="delClass" onclick="removeCat()" data-remove="${JSON.stringify(wizard._id)}" href="#">Delete</a></td>
</tr>`;
})
.join('')
);
Now I want to remove the above elements when clicked but I use getElementsByClassName and other methods but its not working
Error message and code images
new images**********
enter image description here
the html is rendered dynamically
here is the picture
data-remove image here********
You can use .closest() to find the tr and remove it:
function removeCat(e) {
e.closest('tr').remove()
};
<table>
<tr>
<td>1</td>
<td><button onclick="removeCat(this)">-</button>
</tr>
<tr>
<td>2</td>
<td><button onclick="removeCat(this)">-</button>
</tr>
<tr>
<td>3</td>
<td><button onclick="removeCat(this)">-</button>
</tr>
</table>
Beside, I see your delete buttons has class delClass so you can add event listener to this class and avoid inline script. For example:
var elements = document.getElementsByClassName("delClass");
var removeCat = function() {
console.log(this.dataset.remove)
this.closest('tr').remove();
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', removeCat, false);
}
<table>
<tr>
<td>1</td>
<td><button class="delClass" data-remove="1">-</button>
</tr>
<tr>
<td>2</td>
<td><button class="delClass" data-remove="2">-</button>
</tr>
<tr>
<td>3</td>
<td><button class="delClass" data-remove="3">-</button>
</tr>
</table>
You use a query selector and the remove method:
tBody.querySelectorAll('tr').forEach(tr => tr.remove());
Or if your table has other rows you don't want to delete, then you must have a way of targeting those exactly. Either give them some special class, or maybe you can use the ones you've already given:
tBody.querySelectorAll('.tr1, .td1').forEach(tr => tr.remove());
No jQuery involve pls. I am just started learning javascript.
I want to find the class='id' of the table when I clicked on the class='detail' button.
I manage to point to class='id' but I can't get the value out of it, why?
var button = document.getElementsByClassName("detail");
for (var i in button) {
button[i].onclick = function() {
var row = this.closest("tr");
var id = row.getElementsByClassName("id");
var value = id.innerText;
console.log(id);
console.log(value); //show undefined here
}
}
<table>
<tbody>
<tr>
<td class="id">123</td>
<td class="name">abc</td>
<td><button class="detail">detail</button></td>
</tr>
<tr>
<td class="id">456</td>
<td class="name">def</td>
<td><button class="detail">detail</button></td>
</tr>
</tbody>
</table>
where would need to change? I must use class here, as the table generated through javascript. thanks.
getElementsByClassName returns HTMLCollection containing multiple matching elements. Like an array, you can access the first element in the collection with [0]
var button = document.getElementsByClassName("detail");
for (var i in button) {
button[i].onclick = function () {
var row = this.closest("tr");
var id = row.getElementsByClassName("id");
var value = id[ 0 ].innerText;
console.log(id);
console.log(value);
}
}
<table>
<tbody>
<tr>
<td class="id">123</td>
<td class="name">abc</td>
<td><button class="detail">detail</button></td>
</tr>
<tr>
<td class="id">456</td>
<td class="name">def</td>
<td><button class="detail">detail</button></td>
</tr>
</tbody>
</table>
I would like to know how could I assign a table row an id which is systematically as a counter. It can be a string + a counter as follow:
<table>
<tr id="Row1"> # it can be only a number => id="1"
<tr id="Row2"> # it can be only a number => id="2"
<tr id="Row3"> # it can be only a number => id="3"
.....
<tr id="Row5000"> # it can be only a number => id="5000"
</table
Because I have thousands of rows and then could not assign id to them manually. This is why I want to assign them via XSLT. Does anybody know how could I do so? Thanks.
// javascript
var table = document.querySelectorAll('table tr');
{
for(var i=0;i<table.length;i++){
table[i].setAttribute("id",i+1);
}
//jquery
$("table tr").each(function(index,object) {
object.attr("id",(index+1));
})
$("table tr").each(function(i, tr) {tr.id = 'Row' + (i+1);})
explanation: you can find each tr in table and assign id for each one.
First you assign an id attribute to your table like this
<table id="mytable">
<tr></tr>
<tr></tr>
....
</table>
Then add a script at the bottom of your document
<script>
(function() {
var rows = document.getElementById("mytable").rows;
for(var i = 1; i <= rows.length; i++) {
rows[i-1].id = 'Row'+i;
}
})();
Its a pure javascript solution. No jQuery required.
Assign your table an id. here its newTable then iterate and set the attibute
<script>
function getit(){
$('#newTable').find('tr').each(function(index){
var x= this.setAttribute("id","Row"+[index]);
console.log(x);
})
}
</script>
hope that helped.
You Can Use This:
Your CSS
<style>
body {
counter-reset: section;
}
table tbody tr th::before {
counter-increment: section;
content: "Section " counter(section);
}
table tbody tr th::before {
content: counter(section);
}
</style>
Your Html
<table class="table">
<thead>
<tr>
<th colspan="6">
</th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">f1</th>
<th scope="col">f2</th>
<th scope="col">f3</th>
<th scope="col">f4</th>
<th scope="col">f5</th>
</tr>
</thead>
<tbody>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
</tbody>
</table>