Nandhini Devi
Nandhini Devi

Reputation: 99

Dynamically adding image in javascript shows error

I want to dynamically add label and image in my code.When I added label its working fine but when I tried to add image.its not working.

 for(var i=0;i<output.length;i++){
 var shopname=$("<label id="+output[i].branch_id+">"+output[i].myfavourite+"</label>");
 var shopimage=$("<img id="+output[i].image+" float="left" width="100px"/>");
 $("#id").append(shopname).append(shopimage);
 }

Upvotes: 1

Views: 66

Answers (1)

MrCode
MrCode

Reputation: 64526

Your quotes in float="left" and width are the issue because you use double quotes to wrap the string. You can escape them like so:

var shopimage=$("<img id="+output[i].image+" float=\"left\" width=\"100px\"/>");

Although you should be setting float in CSS, not as an attribute:

var shopimage=$("<img id="+output[i].image+" width=\"100px\" style=\"float:left\" />");

The whole code would be better working with objects instead of a HTML string:

var shopname = $("<label></label>")
                   .prop("id", output[i].branch_id)
                   .text(output[i].myfavourite);

var shopimage = $("<img />")
                   .prop("id", "someid")
                   .prop("src", output[i].image)
                   .css({
                       width : '100px;',
                       float: 'left'
                   });

$("#id").append(shopname).append(shopimage);

Upvotes: 4

Related Questions