Home > Blockchain >  How to insert image in table
How to insert image in table

Time:05-13

I need create a table with rows

ID | Image | Info about image

and it's a part of code:

function add(form) {
  table1 = getElementById('mytable');
  row1 = table1.insertRow(table1.rows.length);
  cell1 = row1.insertCell(row1.cell.length);
  cell1 = row1.rowIndex;
}
<table id="mytable" border="1">
  <tr>
    <th>id</th>
    <th>picture</th>
    <th>info</th>
  </tr>
</table>
<br>
<form>
  <input type="text" name="info">
  <input type="file" name="pic" accept="image/png, image/jpeg">
  <input type="button" onclick="add(this.form)" value="Add" /> <br>
  <input type="button" onclick="del(this.form)" value="Delete" />
</form>

I coded only ID. Now I need to insert picture. And I don't know how to do it...

P.S: I'm beginner and doing a practice for college

CodePudding user response:

It should work this way, not tested though (and I smashed some other bugs in your function):

function add(form) {
  table1 = document.getElementById('mytable');
  row1 = table1.insertRow(table1.rows.length);
  cell1 = row1.insertCell(row1.cells.length);
  cell1 = row1.rowIndex;
  cell2 = row1.insertCell(row1.cells.length);
  let file = document.getElementsByName('pic')[0].files[0];
  let src = URL.createObjectURL(file);
  let image = document.createElement('img');
  image.src = src;
  cell2.appendChild(image);
  // ...
}

Reference: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

CodePudding user response:

One way of uploading an image using the image address would be the following: You can try it using any image address from the web (e.g: https://static.thenounproject.com/png/802538-200.png)

In the case of using an image from the user's local disk you could get net::ERR_UNKNOWN_URL_SCHEME due to security risks.

HTML

<table id="mytable" border="1">
  <tr>
    <th>id</th>
    <th>picture</th>
    <th>info</th>
  </tr>
</table>
<br>
<form>
  <label for="id">Id</label>
  <input type="text" name="id" id="id">

  <label for="pic">Picture Path</label>
 <input type="text" name="pic" id="pic">

  <label for="info">Info</label>  
  <input type="text" name="info" id="info">

  <input type="button" onclick="add(this.form)" value="Add" /> 
</form>

JS

    function add() {
  let table = document.getElementById('mytable');
  let row = table.insertRow(0);
  let cell0 = row.insertCell(0);
  let cell1 = row.insertCell(1);
  let cell2 = row.insertCell(2);

  let source = document.getElementById('pic').value;
  let img = document.createElement('img');
  img.setAttribute('src', source);

  cell0.innerHTML = document.getElementById('id').value;
  cell1.appendChild(img);
  cell2.innerHTML = document.getElementById('info').value;
}
  • Related