How to remove an item using class? : javascript - javascript

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>

Related

how to show data to table from an array of objects

I am trying to make a data table from user input. i found out this solution that i am making objects from user input and pushing them to an array. after that, I am doing a for loop to make td. but somehow those datas are not coming line by line but they are coming side by side. what I am doing wrong here and every time I am refreshing the page the array is getting empty how to prevent this help me out tnx.
const form = document.getElementById("form");
const carDatas = [];
class Car {
constructor(plate, carMaker, carModel, carOwner, carPrice, carColor) {
(this.plate = plate),
(this.carMaker = carMaker),
(this.carModel = carModel),
(this.carOwner = carOwner),
(this.carPrice = carPrice),
(this.carColor = carColor);
}
}
form.addEventListener("submit", (e) => {
const plate = document.getElementById("plate").value;
const carMaker = document.getElementById("carMaker").value;
const carModel = document.getElementById("carModel").value;
const carOwner = document.getElementById("carOwner").value;
const carPrice = document.getElementById("carPrice").value;
const carColor = document.getElementById("carColor").value;
const carDetails = new Car(
plate,
carMaker,
carModel,
carOwner,
carPrice,
carColor
);
carDatas.push(carDetails);
console.log(carDetails);
for (let i = 0; i < carDatas.length; i++) {
document.getElementById(
"data"
).innerHTML = ` <td>${carDatas[i].plate} </td>
<td>${carDatas[i].carMaker} </td>
<td>${carDatas[i].carModel} </td>
<td>${carDatas[i].carOwner} </td>
<td>${carDatas[i].carPrice} </td>
<td>${carDatas[i].carColor} </td>`;
}
e.preventDefault();
});
and here is my HTML for the table
<div class="database">
<h1>Cars Database</h1>
<table>
<tr>
<th>LICENCE</th>
<th>MAKER</th>
<th>MODEL</th>
<th>OWNER</th>
<th>PRICE</th>
<th>COLOR</th>
</tr>
<tr id="data"></tr>
</table>
</div>
<pre>This is what I recommend I changed your code to add <tr></tr> to each line that's to be created and wrap your <tr> inbetween and tbody tag and use the first line has a head.</pre>
<pre>For the code:</pre>
<code>
for (let i = 0; i < carDatas.length; i++) {
document.getElementById(
"data"
).innerHTML = `<tr><td>${carDatas[i].plate} </td>
<td>${carDatas[i].carMaker} </td>
<td>${carDatas[i].carModel} </td>
<td>${carDatas[i].carOwner} </td>
<td>${carDatas[i].carPrice} </td>
<td>${carDatas[i].carColor} </td> </tr>`;
}
e.preventDefault();
<body>
<div class="database">
<h1>Cars Database</h1>
<table>
<thead>
<tr>
<th>LICENCE</th>
<th>MAKER</th>
<th>MODEL</th>
<th>OWNER</th>
<th>PRICE</th>
<th>COLOR</th>
</tr>
</thead>
<tbody id="data"> <tbody>
</table>
</div>
</body>
</code>

How to find value of card._id using jQuery?

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>

How to get all the elements of a column from html table and validate if a particular string exists in that list

I have a html table with multiple rows and columns. I want to pull all the values by column id and compare with some matching string. If matches i want to enable a button on the page.
Could you please let me know how to refer the column by id in $(document).ready function.
Here is the table
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th:block th:each="it : ${data}">
<tr>
<td th:text="${it.id}">id</td>
<td th:text="${it.name}">name</td>
<td th:text="${it.place}">place</td>
</tr>
</th:block>
</table>
Button:
style="visibility:hidden">Submit
$(document).ready(function(){
//here i want to pull the place column and verify if one of the
places matches my input string enable submit button
$("#submitbutton").css("visibility", "visible");
}
}
This function will take all information inside you td and search for the string you looking for :
But i cannot get the point that you search for a particular string instead of searching for an object.
const addresses = [...document.querySelectorAll(".address")];
const serchFromList = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).filter(el => el === str)
}
console.log(serchFromList(addresses, "NY"))
/* in case you want a boolean you can use some*/
const isAddressExist = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).some(el => el === str)
}
console.log(isAddressExist(addresses, "NY"))
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th>
<tr>
<td>4545</td>
<td>5454</td>
<td>65687</td>
</tr>
<tr>
<td>aziz</td>
<td>david</td>
<td>paul</td>
</tr>
<tr>
<td class='address'>NY</td>
<td class='address'>MTL</td>
<td class='address'>BC</td>
</tr>
</th>
</table>
Should be pretty doable with XPath if you don't want to add extra attributes to Place cell. Just find out the position of Place column and get the text from the same position of <td>.
// Get the table node first
let node = document.getElementById('data')
// Find out position of `Place` column
let nth = document.evaluate('count(//th[text()="Place"]/preceding-sibling::*)+1', node).numberValue
// Get all the place cell by the position
let placeCells = document.evaluate(`//td[position()=${nth}]`, node)
// Get all the place names
let places = [],
placeNode = placeCells.iterateNext()
while (placeNode) {
places.push(placeNode.textContent)
placeNode = placeCells.iterateNext()
}
console.log(places)
// ['NYC', 'SF', 'LA']
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<tbody>
<tr>
<td>0001</td>
<td>Mary</td>
<td>NYC</td>
</tr>
<tr>
<td>0002</td>
<td>John</td>
<td>SF</td>
</tr>
<tr>
<td>0003</td>
<td>Bob</td>
<td>LA</td>
</tr>
</tbody>
</table>

table row as a counter in HTML

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>

Can I alert() all elements of a javascript array in a single alert?

I have a simple HTML table like this:
<table>
<thead>
<tr>
<th id="lname"><span title="sort this column">Last Name</span>
</th>
<th id="fname"><span title="sort this column">First Name</span>
</th>
<th id="scanned"><span title="sort this column">Scanned In</span>
</th>
<th id="department"><span title="sort this column">Department</span>
</th>
<th id="category"><span title="sort this column">Category</span>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="blah">LNAME1</td>
<td>FNAME1</td>
<td>06/25/13 12:48 PM</td>
<td>Internal Medicine</td>
<td>Fellow</td>
</tr>
<tr>
<td class="blah">LNAME1</td>
<td>FNAME1</td>
<td>06/25/13 12:48 PM</td>
<td>Internal Medicine</td>
<td>Fellow</td>
</tr>
<tr>
<td class="blah">LNAME1</td>
<td>FNAME1</td>
<td>06/26/13 07:29 AM</td>
<td>Internal Medicine</td>
<td>Faculty</td>
</tr>
<tr>
<td class="blah">LNAME1</td>
<td>FNAME1</td>
<td>06/26/13 07:21 AM</td>
<td>Internal Medicine</td>
<td>Faculty</td>
</tr>
</tbody>
</table>
And a javascript/jquery code going something like this:
var count = 0;
var scannedArr = new Array();
$('table tr').each(function(){
var times = $(this).find('.blah').text();
scannedArr[count] = times;
count++;
});
What I'm trying to do in this javascript function is include the scannedArr array's elements all in a single alert(). Can I do that? Is there a simpler way to go about it?
Thanks in advance!
Try this
alert(scannedArr.join(''));
You can use join() to create single string of your array:
// using comma as a separtor
// you can pass any separator as: join('separator')
var everything = scannedArr.join();
alert(everything);
I would do this:
var tableStuff = $('table tr').map(function(){
return $(this).find('.blah').text();
}).get();
alert(tableStuff);
Now tableStuff is a nice array of the text from .blah
I tend to use:
alert(JSON.stringify(scannedArr));
You can use something like:
function printObject(o) {
var out = '';
for (var p in o) {
out += p + ': ' + o[p] + '\n';
}
alert(out);
}
But, i like more use console.log(array), with chrome (and you can see in the js console!)
var count = 0;
var scannedArr = new Array[];
$('table tr').each(function(){
var times = $(this).find('.blah').text();
scannedArr.push(times)
count++;
});
alert(scannedArr);

Categories