Reputation: 59
When im trying to pass object to function, i get "Uncaught syntaxError: Unexpected Identifier".
Code looks like this:
myLibrary = [{author: "J.K.Rowling",
title: "Harry Potter and the Philosopher's Stone",
numberOfPages: 223,
read: true
}];
function displayBooksTable () {
let table = document.getElementById("books-list");
if(myLibrary.length === 0) {
table.textContent = '';
return;
}
table.textContent = '';
myLibrary.forEach((book, index) => {
let row = table.insertRow(-1);
let title = row.insertCell(0);
let author = row.insertCell(1);
let pages = row.insertCell(2);
let read = row.insertCell(3);
let del = row.insertCell(4);
title.innerHTML = book.title;
author.innerHTML = book.author;
pages.innerHTML = book.numberOfPages;
read.innerHTML = '<button id="read-button" onclick="updateReadButton('+book+')">read</button>'
del.innerHTML = '<button id="del-button" onclick="deleteButton('+index+')">Delete</button>'
})
console.table(myLibrary);
}
const updateReadButton = (book) => {
book.read = !book.read;
displayBooksTable();
}
Issue is with this:
read.innerHTML = '<button id="read-button" onclick="updateReadButton('+book+')">read</button>'
and
const updateReadButton = (book) => {
book.read = !book.read;
displayBooksTable();
}
What am I doing wrong? How can i pass book object to function from forEach loop?
Upvotes: 0
Views: 264
Reputation: 370699
The book
is an object, but you're turning it into a string when inserting it into HTML markup here:
onclick="updateReadButton('+book+')"
resulting in problems.
Best to avoid inline handlers entirely - they have problems with quote escaping and a crazy scope chain. Add the event listener to the element using addEventListener
.
read.innerHTML = '<button>read</button>';
del.innerHTML = '<button>Delete</button>';
read.children[0].addEventListener('click', () => updateReadButton(book));
del.children[0].addEventListener('click', () => deleteButton(index));
Upvotes: 4