Displaying images within a table using innerHTML (Javascript / Html)

Let's start off with some important details: I have a dynamic table that is being generated. The structure of the table is as follows:

|item__ | price | category | category | category | category | picture |

|chicken| $20 | _______ |_ ______ | _______ | _______ | 1000.png|

var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        if (j == 6) {
            table += "<td>" + "<img src='CSV_Photos/" + array[i][j] +"' style ='width:500px;height:300px'>";
        } else {
            table += "<td>" + array[i][j];
        }
    table += "</tr>";
    table += "</tr>";
}

document.getElementById("Invtable").innerHTML = table;

The above code snippet showcases my current implementation, where 'array' represents a 2D array. In each row, when it comes to the 6th column, I aim to display an image. Despite running this code, no table is rendered on the screen.

In the following code segment:

var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        table += "<td>" + array[i][j];
    }
    table += "<tr>";
    table += "</tr>";
}

document.getElementById("Invtable").innerHTML = table;

When the conditional statement and image tag are removed from the initial code, the table renders correctly but displays '1000.png' instead of the actual image. The folder 'CSV_Photos' contains the images, located in the same directory. Any suggestions or assistance in resolving this issue would be greatly appreciated.

Update: The second part of the code successfully generates the table without any issues. However, every row's 6th column contains the image name ('1000.png') from the 'CSV_Photos' folder. I intend to have the actual image displayed instead of just the file name. My first attempt at incorporating the image element seems to be causing the problem, leading to the failure of table creation.

Answer №1

It looks like there are a few issues in your code that require some attention:

  • The td elements are not being appended inside the tr but directly within the table. You should move the line table += "<tr>"; before the nested loop.
  • You are missing closing tags for the <td> elements, which can impact the layout when including the img tag.
  • Make sure to switch the usage of double quotes (") and single quotes (') in your img tag definition since HTML uses double quotes to define attributes.

Here is how your code should be structured:

var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
  table += "<tr>";
  for (var j = 0; j < array[i].length; j++) {
    if (j == 6) {
      table += "<td>" + '<img src="CSV_Photos/' + array[i][j] + '" style ="width:500px;height:300px"></td>';
    } else {
      table += "<td>" + array[i][j] + "</td>";
    }
  }
  table += "</tr>";
}

document.getElementById("Invtable").innerHTML = table;

Answer №2

Give this a shot:

    let dataArray = getCSVData();
    let htmlTable = "<table>";
    for (let i = 0; i < dataArray.length; i++) {
        htmlTable += "<tr>";

        for (let j = 0; j < dataArray[i].length; j++) {
            htmlTable += "<td>" + dataArray[i][j];
        }

        htmlTable += "</tr>";
    }
    htmlTable += "</table>";

    document.getElementById("ResultsTable").innerHTML = htmlTable;

Answer №3

  • To place the image on the 2nd row, 3rd cell, use this condition:
if (i === 1 && j === 2) {...
  • If you wish to have the same image in each cell of the 2nd row, the condition should be:
if (i === 1) {...
  • To assign the same image to the entire 3rd column, the condition would be:
if (j === 2) {...
  • If each cell requires a different image, name the files based on table coordinates such as...
img1-2.png

...then update the string that displays an image in a cell to:

 table += `<td><img src='http://imgh.us/img${i}-${j}.png' style ='width:50px;height:50px'></td>`
  • Alternatively, if the array already contains filenames, modify the string as follows:
 table += `<td><img src='http://imgh.us/${array[i][j]}' style ='width:50px;height:50px'></td>`

... and the array structure could be like:

  var array = [
      ['rt','AD','1000.png','uy','ii'],
      ['rt','AD','1001.png','uy','ii'],
      ['rt','AD','1002.png','uy','ii']
    ];

By the way, some adjustments were made to the code for functionality since it was incomplete, with the primary focus being on the conditions.

You may notice the unique syntax of the strings, which is ES6 template literals or "strings on steroids".

Demo

var array = cvpls();
var table = ``;
for (var i = 0; i < array.length; i++) {
  table += `<tr>`;
  for (var j = 0; j < array[i].length; j++) {
    if (i === 1 && j === 2) {
      table += `<td><img src='http://imgh.us/statik.gif' style ='width:50px;height:50px'></td>`;
    } else {
      table += `<td>${array[i][j]}</td>`;
    }
  }
  table += `</tr>`;
  document.getElementById("Invtable").innerHTML = table;
}

function cvpls() {
  return array = [
    [4, 5, 6, 9, 2],
    ['img', 'img', 'img', 'img', 'img'],
    ['d', 'b', 'g', 'i', 'o']
  ];
}
td {
  border: 1px solid black
}
<table id='Invtable'></table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoking a PHP class through an AJAX response handler code

I'm attempting to access a PHP-File using AJAX. When I use a basic PHP-File like this: <?php header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: must-revalidate, pre-check=0, no-store, no-cache, max-age=0, pos ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

There seems to be a glitch in the AJAX code

I am currently working on a project that involves displaying categories and subcategories of products on a webpage. When users click on either a category or a subcategory, AJAX is used to send the selected item to a php script which then generates HTML cod ...

Encountering an unexpected token error while using Webpack with React modules

I've been attempting to utilize the react-spin npm package, but when I try to create a bundle.js with webpack, an error occurs: Module parse failed: /Users/nir/browsewidget/node_modules/react-spin/src/main.js Line 29: Unexpected token < You may ne ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

How can I use the .filter() method in JavaScript to retrieve the last X elements/indices from an array?

I am searching for a method to sift through an array and retrieve the last x number (or most recently added) of elements/indices from that array. While I understand that .pop() may be a possibility, I am uncertain about how to integrate ...

Seamlessly replacing an image in PixiJS without any sudden movement

I'm currently developing a HTML5 JavaScript game with a heavily textured background. My goal is to incorporate a 3D background element that can be swapped out dynamically. For example, the initial scene may show a room with a closed door, but once a J ...

Image proxy in Node.js

I am currently working on creating a proxy for images using an input URL. Although my code is set up to copy the same headers and return them to the client, I have encountered issues where the response either continues loading indefinitely or shows an er ...

Using the map function to iterate over an array of objects retrieved from GetStaticProps in NextJS

Currently, I am working on a mdx blog within the NextJS framework. To achieve this, I have implemented a function called getPostDataByCategory(category) in posts.js located under lib. This function is responsible for filtering posts based on categories. ge ...

Displaying JSON information in an HTML table with JavaScript

I successfully displayed JSON data in an HTML table. Here is the snippet I used: $("#example-table").tabulator({ height:"300px", fitColumns:true, tooltips:true, columns:[ {title:"Month", field:"Month", sorter:"string"}, {title:"Numbers", ...

Imitate a hover effect followed by a click to activate the pre-established onclick function

When using Gmail, selecting a message will prompt a bar to appear at the top of the messages table. This bar allows for mass actions to be performed on the selected messages (refer to the GIF photo attached). https://i.stack.imgur.com/XxVfz.gif I have be ...

Utilize MaterialUI's stepper component to jazz up your design with

Is there a way to customize the color of a material ui Stepper? By default, the material UI stepper's icons use the primary color for both "active" and "completed" steps. class HorizontalLinearStepper extends React.Component { state = { activeS ...

"Node.js is throwing a 'postgres: relation does not exist' error even though the table it's referring to

After executing a psql command to create table users, I encountered some issues. CREATE TABLE users ( id integer NOT NULL, username text ); Although I can retrieve rows with SELECT * FROM users; When using node.js and the pg module for making c ...

JavaScript module encounters an uncaught error: Attempting to assign a value to a constant variable

In another module, I defined a variable in the following manner: // module1.js let directory; export { directory }; Now, I am trying to access it in a separate module like so: // module2.js import { directory } from '../js/module1.js'; directo ...

Ways to guide users through a single-page website using the URL bar

I currently have a one-page website with links like <a href="#block1">link1</a>. When clicked, the browser address bar displays site.com/#block1 I am looking to modify this so that the browser shows site.com/block1, and when the link is clicke ...

I am seeing the object in req.body displayed in reverse order within my Node.js and Express backend application

I encountered an issue while developing a To-do list web application using the MERN stack with Redux. The problem arises when I try to send post data to the backend. In my form, the textfield area is named 'task' (e.g., ) and I input 'jonas& ...

What steps should one take to address issues related to Datatables in Laravel and Vue?

I encountered an issue while trying to fetch data into a datatable in Laravel. I am receiving an error message stating "Uncaught ReferenceError: $ is not defined" on the console of the page. Is there a solution to resolve this problem? index.blade.php ...

Error encountered when attempting to retrieve HTML content from localhost using AJAX

Attempting to insert HTML code into a div element using ajax, similar to how it's done with an iframe. Testing this out locally first to avoid Same Origin Policy complications. The web application is currently hosted on a wamp server. There are two ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

Transforming the appearance of the menu element in Vue using transitions

In my Vue app, I have this SCSS code that I'm using to create a smooth transition effect from the left for a menu when the isVisible property is set to true. However, I am encountering an issue where the transition defined does not apply and the menu ...