Necesito crear una tabla con filas.
identificación | Imagen | Información sobre la imagen
y es parte del código:
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>Solo codifiqué DNI. Ahora necesito insertar una imagen. Y no se como hacerlo...
PD: soy principiante y estoy haciendo una practica para la universidad
Debería funcionar de esta manera, aunque no probado (y eliminé algunos otros errores en su función):
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); // ... }Referencia: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
Una forma de cargar una imagen usando la dirección de la imagen sería la siguiente: Puede probarlo usando cualquier dirección de imagen de la web (por ejemplo: https://static.thenounproject.com/png/802538-200.png )
En el caso de usar una imagen del disco local del usuario podría obtener net::ERR_UNKNOWN_URL_SCHEME debido a riesgos de seguridad.
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; }