Reputation: 6829
I use ajaxForm
to upload image. On success upload I add uploaded image to div
on the page:
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
...
success: function (result) {
$("#imageList").prepend('<img src=' + result.message + '/>');
Now I was thinking that it is not smart to put this hardcoded <img/>
tag in javascript code.
What is the best way to put image but not use img
tag in prepend() function?
Upvotes: 0
Views: 165
Reputation: 12916
Use a template. For instance:
<div style="display:none">
<!-- This div contains all your templates -->
<img src="about:blank" class="classesYouNeed" id="uploadSuccess">
</div>
and then use javascript:
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
...
success: function (result) {
var img = $('#uploadSuccess')
.clone()
.attr('id', somethingElse)
.attr('src', result.message)
$("#imageList").prepend(img);
})
})
There are jQuery templating frameworks out there that will make this much easier.
Upvotes: 1
Reputation: 22007
IMHO that is the best way, there's no need to change anything. If you don't want to dynamically append/detach, you could have an existing img
as a placeholder and just change its src
attribute when you wanted to change it:
<img id="placeholder" src="initial/path" />
$("#placeholder").attr("src", result.message);
But since you're dealing with an image list, as your code suggested, I think your original solution is more appropriate for your case. If you ever decide to remove an image or sort the list or whatever, you can selected them using $("imageList img")
.
Edit: OTOH if you have a very complex structure, that you want to code in HTML but also need to make dynamic copies of it, you can use clone
as an alternative:
<div id="model" style="display:none">complex markup goes here</div>
$("#model").clone().attr("id",anotherID).appendTo(target).show();
Upvotes: 1
Reputation: 37815
i would not have any problem with that... unless you are worried about invalid url that could break the tag...
you could use simple javascript
var img = new Image();
img.src = result.message;
$("#imageList").prepend(img);
Upvotes: 2