I am new to Javascript/JQuery and am looking for input on how to create a ul of images based on data returned from an AJAX call. I am using $.getJSON and $.each to retrieve and iterate over the JSON. I am also using $.('image_list').html() to insert the generated markup into the div placeholder.
What I'm not sure of is how best to generate the markup and to bind an event that when the image is clicked, a function sets a couple of hidden input fields (src = blog_style_url, title = title, and alt = description).
The AJAX call returns data in the following format:
[{"description":"lorem ipsum","id":6,"title":"saepe atque doloremque minus","thumb_style_url":"/system/files/6/thumb/image.png?1306422297","blog_style_url":"/system/files/6/blog/image.png?1306422297"}]
This is what I have so far, which doesn't work but will hopefully give an idea of what I'm trying to do.
<script>
function select_image(url, alt, title){
$("#src").val(url);
$("#alt").val(alt);
$("#title").val(title);
}
$(document).ready(function() {
$.getJSON('/api/images.json', function(data) {
var items = [];
//$.each(data, function(index, image) {
//items.push('<li><a href="javascript:void(0)" onclick="db_insert_image(\'' + image.blog_style_url + '\', \'something\')"><img src="' + image.thumb_style_url + '" /></a></li>');
//console.log($('<img />', { 'src' : image.thumb_style_url }));
//<li><a><img /></a></li>
//});
$('#dynamic_images_list').html(function() {
$.each(data, function(index, image) {
$('<img />', {'src' : image.thumb_style_url});
});
});
$("img").click(function(){
alert('hello world!');
});
});
});
</script>
This is what I'd like the final output to look like:
// The generated markup
<div id="image_list>
<ul>
<li><a ..><img src="/system/files/6/thumb/image.png?1306422297" title="saepe atque doloremque minus" alt="lorem ipsum" /></a></li>
</ul>
</div>
And then have an event bound to click that sets the hidden attributes as described above.