Vinay
Vinay

Reputation: 15

Javascript add button to table

This is part of my code for the table. it works but I would like to add button

var html = "<table>";

for(var i=0; i<prodArray.length; ++i){
  htmlStr += "<td>" + prodArray[i].name + "</td>";
  htmlStr += "<tr>";
  htmlStr += "<td><img width=200 height=200 src='" + prodArray[i].image_url + 
 "'></td>";
  htmlStr += "<td>" + prodArray[i].price + " coins" + "</td>";
  // This bit with the button is not working
  htmlStr += "<td><button type=button> Click Me!</button"'></td>";
  htmlStr += "</tr>";
}

Please help.

Upvotes: 0

Views: 195

Answers (3)

Aziz.G
Aziz.G

Reputation: 3721

Is better to use `` so it can be easy to read

const prodArray = [{
  name: "user3",
  image_url: "https://picsum.photos/200/300",
  price: "100"
}, {
  name: "user2",
  image_url: "https://picsum.photos/200/300",
  price: "100"
}];

var htmlStr = "<table>";

prodArray.map((el, index) => {
  htmlStr += `<td>" ${el.name}"</td>`;
  htmlStr += `<tr>`;
  htmlStr += `<td><img width=200 height=200 src=" ${el.image_url}"></td>`;
  htmlStr += `<td> ${el.price} coins</td>`;
  htmlStr += `<td><button type=button> Click Me!</button></td>`;
  htmlStr += `</tr>`;
})


htmlStr += `</table>`;

document.getElementById("table").innerHTML = htmlStr;
<div id="table"> </div>

Upvotes: 2

A. Meshu
A. Meshu

Reputation: 4148

You escaping the quote. Try this:

htmlStr += "<td><button type='button'> Click Me!</button></td>";

Upvotes: 0

rgamec
rgamec

Reputation: 1

There's a small syntax error breaking your <button> tag.

Try this modified code below. Also take care with the variable naming, you're declaring the var "html" but then refer to "htmlStr" in your for-loop.

htmlStr += "<td><button type=\"button\"> Click Me!</button></td>";

You might find this page on w3schools useful for more details on the <button> tag.

Upvotes: 0

Related Questions