0

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.

3
  • Where do you want to add the button? Commented Feb 5, 2019 at 21:35
  • 1
    For one thing, you've got var html = '<table>';, but then you add to htmlStr, a different variable. It would be better if you could use Stack Snippets to provide an minimal reproducible example. Commented Feb 5, 2019 at 21:36
  • You have some syntactical issues on line 8. It should be "<td><button type=button> Click Me!</button></td>"; without the quote marks inside the </button> tag Commented Feb 5, 2019 at 21:36

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

You escaping the quote. Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.