Tarvo Mäesepp Tarvo Mäesepp - 5 days ago 5
jQuery Question

Append table with images from Firebase

I am trying to append table with images. But for some reason it is not displaying them. What can cause this?

This is the

jquery
:

$(document).ready(function() {
var brandsRef = firebase.database().ref().child("Snuses");
brandsRef.on("child_added", snap=> {
var productImageUrl = snap.child("productUrl").val(); //This is the image src
var brandName = snap.child("Brand").val();
var product = snap.child("Products").val();
var nicotine = snap.child("nicotine").val();

$("#tableBody").append("<tr>"
+ "<td>"+$("img").attr("src", productImageUrl);+"</td>" //Is this right way to do it?
+ "<td>"+brandName+"</td>"
+ "<td>"+product+"</td>"
+ "<td>"+nicotine+"</td>"
+ "</tr>");

})
});

Answer

$("img") just grabs all the images on the page as it's treated as a CSS selector. What you probably wanted was $("<img/>").

In general, your code should probably look something like:

var $row = $('<tr></tr>').appendTo('#tableBody');
$('<td></td>').appendTo($row).append($('<img />').attr('src', productImageUrl));
$('<td></td>').appendTo($row).text(brandName);
$('<td></td>').appendTo($row).text(product);
$('<td></td>').appendTo($row).text(nicotine);
Comments