1

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);
 }
1
  • use single quote instead of double quotes Commented Jun 25, 2014 at 10:04

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

5 Comments

You aren't setting any src attribute of the image, so nothing will show. Try adding that.
var shopimage=$("<img id="+i+"src="+output[i].image+" float=\"left\" width="100px"/>"); still not working
You need a space before src. Anyway see my edit for a better way.
size of image not changing even though i gave the size for it @mrcode
@NandhiniDevi use quotes around 'margin-left' because it contains a special character. Also you didn't include jQuery in the fiddle. Working: jsfiddle.net/2b6LL/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.