Reputation: 39
Hi I'm stuck on a university project at the moment where I created an array of images like so:
var testdata = [
{
"imageID": 17,
"uploadedDate": "2020-07-31 03:56:56.243139",
"filepathOriginal": "test_images/image1.jpg"
},
{
"imageID": 18,
"uploadedDate": "2020-07-31 04:06:14.711057",
"filepathOriginal": "test_images/image2.jpg"
},
{
"imageID": 19,
"uploadedDate": "2020-07-31 04:08:10.360168",
"filepathOriginal": "test_images/image3.jpg"
}
];
I need to iterate through this array and display each image on the screen inside a modal for a user to be able to see. I'm a bit unsure how to do this, I thought that a for-loop would be best, but alas I can't get it to work. Is anybody able to help me out with this one?
Here is the HTML code for the modal:
<!--modal header: includes functional closing button for modal to return to page-->
<div class="modal-header">
<span class="closeBtn">×</span>
<h2>Image search and processing</h2>
<p>Please select the dates you wish to search: </p>
</div>
<div class="modal-body">
<form id="modal-form" class="form" >
<!--date picker for querying API-->
<input id="datepicker"/>
<button id="submit">Submit</button>
<script type="text/javascript" src="js/pipeline.js"></script>
<!--floating buttons to submit process or clear form/array and return to page-->
<button type="submit" class="floating-btn" value ="submit">+</button>
<button type="reset" class="floating-btn2" value ="reset" onclick="return hideImage()">x</button>
<!--hidden input that adds selected images to an array for processing-->
<input type="hidden" name="list" id="list">
</form>
</div>
Any help on this would be greatly appreciated!!
Upvotes: 0
Views: 445
Reputation: 887
There are many ways you can approach this, a for loop can work. In my example, I used forEach as it involves less writing and essentially works the same way. With a forEach loop, you iterate through each element in the given array in order.
My function is saying to get the array "testdata", iterate through each data item, and for each data item, get the element "#demo" and update the html to output a paragraph tag containing the imageID from the object. I did this as an example, you can use the same model to output an image tag using the filepathOriginal from the object. The "+=" just means after each call to APPEND the new paragraph tag instead of replacing the old one.
var testdata = [
{
"imageID": 17,
"uploadedDate": "2020-07-31 03:56:56.243139",
"filepathOriginal": "test_images/image1.jpg"
},
{
"imageID": 18,
"uploadedDate": "2020-07-31 04:06:14.711057",
"filepathOriginal": "test_images/image2.jpg"
},
{
"imageID": 19,
"uploadedDate": "2020-07-31 04:08:10.360168",
"filepathOriginal": "test_images/image3.jpg"
}
];
testdata.forEach(data => {
document.getElementById("demo").innerHTML += '<p>' + data.imageID + '</p>';
})
<div id="demo"></div>
Upvotes: 2