I'm solving this problem, I want to add and remove items to the HTML table using javascript. So far I've got this, but I don't really know how to make the removing part possible. Could you give me a hand please?
let inputJmeno = document.querySelector('#inputJmeno');
let inputPrijmeni = document.querySelector('#inputPrijmeni');
let inputVek = document.querySelector('#inputVek');
let buttonAdd = document.querySelector('#add');
let table = document.querySelector('table');
let tbody = document.querySelector('tbody');
let tr = document.querySelector('tr');
let jmeno = null;
let prijmeni = null;
let vek = null;
let pocetOsob = 0;
buttonAdd.addEventListener('click', add);
function add() {
jmeno = inputJmeno.value;
prijmeni = inputPrijmeni.value;
vek = inputVek.value;
let newRow = document.createElement('tr');
let newJmeno = document.createElement('td');
let newPrijmeni = document.createElement('td');
let newVek = document.createElement('td');
let krizek = document.createElement('span');
krizek.id = "krizek" + pocetOsob;
krizek.className = "krizClass";
newRow.id = "row" + pocetOsob;
newJmeno.innerHTML = jmeno;
newPrijmeni.innerHTML = prijmeni;
newVek.innerHTML = vek;
krizek.innerHTML = 'x';
tbody.appendChild(newRow);
newRow.appendChild(newJmeno);
newRow.appendChild(newPrijmeni);
newRow.appendChild(newVek);
newRow.appendChild(krizek);
load(pocetOsob);
pocetOsob++;
}
function load(p) {
let krz = document.querySelector('#krizek'+p);
console.log(p);
}
try
newRow.removeChild(krizek);
Related
I want to select all elements using querySelectorAll with variable "amountClass" but NodeList always is empty
function addingCoin() {
const table = document.querySelector('.list__table');
table.addEventListener('submit', (event) => {
event.preventDefault();
const walletCryptos = document.querySelector('#usersCrypto');
const coinAmount = event.target.inputAmount;
const coinRow = coinAmount.parentElement.parentElement.parentElement;
const coinName = coinRow.querySelector('.name').textContent;
const coinPrice = coinRow.querySelector('.price').textContent.match(/\d+(\.\d+)?/)[0];
const coinValue = coinAmount.value*coinRow.querySelector('.price').textContent.match(/\d+(\.\d+)?/)[0];
let amountClass = coinName;
let existingCoin = document.querySelectorAll(amountClass);
if (existingCoin.length > 0) {
existingCoin[0].innerText = coinAmount.value +
existingCoin[0].value;
} else {
const newTr = document.createElement("tr");
const nameTh = document.createElement("th");
const priceTh = document.createElement("th");
const amountTh = document.createElement("th");
const valueTh = document.createElement("th");
nameTh.innerText = coinName;
if (coinPrice < 0.95) {
priceTh.innerText = parseFloat(coinPrice).toFixed(8);
} else {
priceTh.innerText = parseFloat(coinPrice).toFixed(2);
};
amountTh.innerText = coinAmount.value;
amountTh.className += coinName;
if (coinValue < 0.95) {
valueTh.innerText = parseFloat(coinValue).toFixed(8);
} else {
valueTh.innerText = parseFloat(coinValue).toFixed(2);
};
walletCryptos.appendChild(newTr);
walletCryptos.appendChild(nameTh);
walletCryptos.appendChild(priceTh);
walletCryptos.appendChild(amountTh);
walletCryptos.appendChild(valueTh);
}});
};
I think the problem may be with this part of code:
let existingCoin = document.querySelectorAll(amountClass);
What can i change to make this work properly? Is there any other solution to check does the element with the certain class exist?
You need a . at the beginning to select a class.
Trim the text content in case it has whitespace around the text.
const coinName = coinRow.querySelector('.name').textContent.trim();
let amountClass = '.' + coinName
Finally I have found the solution:
const amountClass = '.' + coinName;
const existingCoin = document.querySelectorAll(amountClass.replace(/ /g,''));
I want to use function instead of codes that I wrote in map method and I want to call this function (createItemCart) inside map method but I don't know how to do it.
This is createItemCart function:
const product = event.target.parentElement;
const id = product.id;
const imgProduct = product.querySelector("img").src;
const titleProduct = product.querySelector(".title").innerText;
const priceProduct = Number(product.querySelector(".price").innerText);
const qtyCheck = document.getElementById("item" + id);
let totalPrice = Number(document.querySelector(".total-price").innerText);
document.querySelector(".total-price").innerText = totalPrice + priceProduct;
function createItemCart(imgProduct, titleProduct, priceProduct, totalPrice, id) {
const itemsCart = document.getElementById("items-cart");
document.querySelector(".total-price").innerText = totalPrice + priceProduct;
const item = document.createElement("div");
item.setAttribute("class", "item-cart");
const imgItem = document.createElement("img");
imgItem.src = imgProduct;
const detailItem = document.createElement("div");
const titleItem = document.createElement("div");
titleItem.setAttribute("class", "title-item");
titleItem.innerText = titleProduct;
const divPrice = document.createElement("div");
const priceItem = document.createElement("span");
priceItem.setAttribute("class", "price-item");
priceItem.innerText = priceProduct;
const spanToman = document.createElement("span");
spanToman.innerText = "تومان";
const qtyItem = document.createElement("div");
qtyItem.className = "qty-item";
qtyItem.innerText = "1";
qtyItem.id = "item" + id;
const deleteItem = document.createElement("i");
deleteItem.className = "delete-item";
deleteItem.innerText = "x";
deleteItemCart(deleteItem, totalPrice, priceProduct);
detailItem.appendChild(titleItem);
detailItem.appendChild(divPrice);
detailItem.appendChild(qtyItem);
divPrice.appendChild(priceItem);
divPrice.appendChild(spanToman);
item.appendChild(imgItem);
item.appendChild(detailItem);
item.appendChild(deleteItem);
itemsCart.appendChild(item);
}
This is map method:
items.map((itemCart) => {
const item = document.createElement("div");
item.setAttribute("class", "item-cart");
const imgItem = document.createElement("img");
imgItem.src = itemCart.img;
const detailItem = document.createElement("div");
const titleItem = document.createElement("div");
titleItem.setAttribute("class", "title-item");
titleItem.innerText = itemCart.title;
const divPrice = document.createElement("div");
const priceItem = document.createElement("span");
priceItem.setAttribute("class", "price-item");
priceItem.innerText = itemCart.price;
const spanToman = document.createElement("span");
spanToman.innerText = "تومان";
const qtyItem = document.createElement("div");
qtyItem.className = "qty-item";
qtyItem.innerText = itemCart.qty;
qtyItem.id = "item" + itemCart.id;
totalPrice += itemCart.price * itemCart.qty;
document.querySelector(".total-price").innerText = totalPrice;
sumQty += itemCart.qty;
document.getElementById("number").innerText = sumQty;
const deleteItem = document.createElement("i");
deleteItem.className = "delete-item";
deleteItem.innerText = "x";
deleteItemCart(deleteItem, totalPrice, itemCart.price);
detailItem.appendChild(titleItem);
detailItem.appendChild(divPrice);
detailItem.appendChild(qtyItem);
divPrice.appendChild(priceItem);
divPrice.appendChild(spanToman);
item.appendChild(imgItem);
item.appendChild(detailItem);
item.appendChild(deleteItem);
itemsCart.appendChild(item);
});
For example I don't know how to use itemCart.img in createItemCart Function. Anyone can help?
You don't use itemCart.img in the function, you use it as the argument to the function.
items.forEach(itemCart =>
createItemCart(itemCart.img, itemCart.title, itemCart.price, itemCart.price * itemCart.qty, itemCart.id));
And you should use forEach() rather than map(). map() is used when you want to create an array of the results of the function, but your function doesn't return anything.
I am using ReactJS and I am creating a button "remove" in a method called showData() and appending it to a row in a table of people.
I am setting its attribute onclick to my method removePerson() implemented in the same class of the method showData().
This is all good until I click on the button "remove" - then an error shows:
ReferenceError: removePerson() is not defined at HTMLButtonElement.onclick
This is my code:
showData() {
let localStoragePersons = JSON.parse(localStorage.getItem("personsForms"));
persons = localStoragePersons !== null ? localStoragePersons : [];
let table = document.getElementById('editableTable');
let x = table.rows.length;
while (--x) {
table.deleteRow(x);
}
let i = 0;
for (i = 0; i < persons.length; i++) {
let row = table.insertRow();
let firstNameCell = row.insertCell(0);
let lastNameCell = row.insertCell(1);
let birthdayCell = row.insertCell(2);
let salaryCell = row.insertCell(3);
let choclatesCell = row.insertCell(4);
let genderCell = row.insertCell(5);
let workTypeCell = row.insertCell(6);
let hobbiesCell = row.insertCell(7);
let descriptionCell = row.insertCell(8);
let colorCell = row.insertCell(9);
firstNameCell.innerHTML = persons[i].firstName;
lastNameCell.innerHTML = persons[i].lastName;
birthdayCell.innerHTML = persons[i].birthday;
salaryCell.innerHTML = persons[i].salary;
choclatesCell.innerHTML = persons[i].Choclates;
genderCell.innerHTML = persons[i].Gender;
workTypeCell.innerHTML = persons[i].workType;
hobbiesCell.innerHTML = persons[i].Hobbies;
descriptionCell.innerHTML = persons[i].Description;
colorCell.innerHTML = persons[i].favoriteColor;
colorCell.style.backgroundColor = persons[i].favoriteColor;
let h = persons[i].ID;
let removeButton = document.createElement('button');
removeButton.setAttribute('onclick', 'removePerson(' + h + ')')
removeButton.innerHTML = 'Remove';
row.appendChild(removeButton);
}
}
I tried to change the code
removeButton.setAttribute('onclick', 'removePerson(' + h + ')');
to
removeButton.onclick = this.removePerson(h);
but everyTime the "showData()" method runs this method "removePerson()" run also and i don't want this to happen.
removePerson(ID) {
alert(ID);
let table = document.getElementById('editableTable');
if (persons.length === 1) {
table.deleteRow(1);
persons.pop();
localStorage.setItem("personsForms", JSON.stringify(persons));
}
let target;
let i;
for (i = 0; i < persons.length; i++) {
if (persons[i].ID === ID) {
target = persons[i].firstName;
persons.splice(i, 1); break;
}
}
for (i = 1; i < table.rows.length; ++i) {
let x = table.rows[i];
if (x.cells[0].innerHTML === target) {
table.deleteRow(i); break;
}
}
let temp = [];
let j = 0;
for (i = 0; i < persons.length; ++i) {
if (persons[i] !== null) {
temp[j++] = persons[i];
}
}
persons = temp;
localStorage.clear();
localStorage.setItem("personsForms", JSON.stringify(persons));
this.showData();
}
When you set a variable to some value, the value is computed first.
Hence, when you write removeButton.onclick = this.removePerson(h); the right side of the equation is evaluated first.
You can wrap it with a fat-arrow function, so that the function that will be called upon user click would be the function that calls this.removePerson(h). This way its value is a lambda function, and not the actual value of this.removePerson(h):
removeButton.onclick = () => this.removePerson(h);
Problem: Trying to get certain elements from a associative array, by using a loop. The loop is for multiple times i will go through. This associative array is associated to an array key. Ex: {eid0:{...},eid1:{...}}
It's to update a page with JS using DOM an no refresh. I've gone over StackOverflow and some other sites. I've looked in books. I can't seem to figure it out.
function display_oddsbet(id) {
var ds = document.getElementById("ds");
var tr = document.createElement("tr");
var td = document.createElement("td");
var tr0 = document.createElement("tr");
var tr1 = document.createElement("tr");
var tbl = document.createElement("table");
var tdsp = document.createElement("td");
var tdlg = document.createElement("td");
var tdloc = document.createElement("td");
var tda = document.createElement("td");
var tdh = document.createElement("td");
var tdsd = document.createElement("td");
var i;
var cnt= 0;
for (var s in id) {
var v = id[s];
for (var t in v) {
var k = v[t];
// for (var f in k) {
var ed = "eid" + cnt;
var i = v[ed];
cnt++;
console.log(i);
tr.classList = "eid" + cnt;
var a = i.awayteam_name;
var h = i['hometeam_name'];
var sd = i['startdate'];
var sport = i['sport_name'];
var league = i['league_name'];
var loc = i['location_name'];
tdsp.innerHTML = sport;
tdlg.innerHTML = league;
tdloc.innerHTML = loc;
tr0.appendChild(tdsp);
tr0.appendChild(tdloc);
tr0.appendChild(tdlg);
tbl.appendChild(tr0);
tda.innerHTML = a;
tdh.innerHTML = h;
tdsd.innerHTML = sd;
tr1.appendChild(tdsd);
tr1.appendChild(tda);
tr1.appendChild(tdh);
tbl.appendChild(tr1);
tr.appendChild(tbl);
// left
if (i['oddsbet'] == "1") {
td.innerHTML = "1";
td.style = "oddsbet";
tr.appendChild(td);
}
// 2 is on right
if (i['oddsbet'] == "2") {
td.innerHTML = "2";
td.classList = "oddsbet";
tr.appendChild(td);
}
// middle
else {
td.innerHTML = i['oddsbet'];
td.classList = "oddsbet";
tr.appendChild(td);
}
ds.appendChild(tr);
// }
}
}
return;
}
I get nothing doing this. I need to get i['awayteam_name']; and the rest from an API.
Don't ever forget. Garbage in Garbage out..
function display_oddsbet(id) {
var ds = document.getElementById("ds");
var tr = document.createElement("tr");
var td = document.createElement("td");
var tr0 = document.createElement("tr");
var tr1 = document.createElement("tr");
var tbl = document.createElement("table");
var tdsp = document.createElement("td");
var tdlg = document.createElement("td");
var tdloc = document.createElement("td");
var tda = document.createElement("td");
var tdh = document.createElement("td");
var tdsd = document.createElement("td");
Object.keys(id).forEach(function(key, index) {
var j = this[key];
Object.keys(j).forEach(function(key, index) {
//console.log(this[index]);
var ed = "eid" + cnt;
//var i = v[ed];
cnt++;
console.log(j[key]);
tr.classList = "eid" + cnt;
var a = j[key].awayteam_name;
var h = j[key]['hometeam_name'];
var sd = j[key]['startdate'];
var sport = j[key]['sport_name'];
var league = j[key]['league_name'];
var loc = j[key]['location_name'];
tdsp.innerHTML = sport;
tdlg.innerHTML = league;
tdloc.innerHTML = loc;
tr0.appendChild(tdsp);
tr0.appendChild(tdloc);
tr0.appendChild(tdlg);
tbl.appendChild(tr0);
tda.innerHTML = a;
tdh.innerHTML = h;
tdsd.innerHTML = sd;
tr1.appendChild(tdsd);
tr1.appendChild(tda);
tr1.appendChild(tdh);
tbl.appendChild(tr1);
tr.appendChild(tbl);
// left
if (j[key].oddsbet == "1") {
td.innerHTML = "1";
td.style = "oddsbet";
tr.appendChild(td);
}
// 2 is on right
if (j[key].oddsbet == "2") {
td.innerHTML = "2";
td.classList = "oddsbet";
tr.appendChild(td);
}
// middle
else {
td.innerHTML = j[key].oddsbet;
td.classList = "oddsbet";
tr.appendChild(td);
}
ds.appendChild(tr);
// }
}, j);
}, id);
return;
}
I'm trying to generate a table dynamically using a userscript.
var divWrap = document.createElement('div');
divWrap.style.fontFamily = "sans-serif";
divWrap.style.width = "100%";
var spanTitle = document.createElement('span');
spanTitle.style.marginRight = "auto";
spanTitle.style.marginLeft = "auto";
spanTitle.style.fontSize = "1.5em";
spanTitle.innerHTML = "Countdown";
divWrap.appendChild(spanTitle);
var createTable = document.createElement('table');
createTable.style.marginLeft = "auto";
createTable.style.marginRight = "auto";
createTable.style.width = "50%";
createTable.id = "cdn_table"
divWrap.appendChild(createTable);
createTable.appendChild(addRow("test", "12d"));
createTable.appendChild(addRow("test2", "24h"));
mainDiv.getElementsByTagName('span')[0].appendChild(divWrap);
function addRow(rName, rValue) {
console.log(rName + ": " + rValue);
var row = document.createElement('tr');
var tName = document.createElement('td');
tName.innerHTML = rName;
var tValue = document.createElement('td');
tValue.innerHTML = rValue;
row.appendChild(tName);
row.appendChild(tValue);
return row;
}
The problem is that all elements are rendered in one line like this: http://i.imgur.com/MjMtdDg.png
Is there some css value I'm missing? Or something else? I want to insert simple title and table in that thumbnail with Scriptish in Firefox..
Tables have their own interface for adding rows/cells.
var t = document.createElement("table");
var r = t.insertRow(-1);
var c = r.insertCell(-1);
c.innerHTML = "Foo";
c = r.insertCell(-1);
c.innerHTML = "Bar";
document.body.appendChild(t);
http://jsfiddle.net/tQWm8/1/