Hi Developers,
In this example when the images are selected the onchange function gets triggered when the input gets changed.
Then the function to clear if any already selected images previews in the upload preview section. And then the for loop gets executed to render the selected images for the upload in the uploads preview section.
<!DOCTYPE html>
<html>
<head>
<style>
.upload-container {
text-align: center;
margin: 20px;
}
.image-preview {
display: flex;
flex-wrap: wrap;
}
.image-preview img {
max-width: 100px;
margin: 10px;
}
</style>
</head>
<body>
<div class="upload-container">
<input type="file" id="image-upload" multiple>
<div class="image-preview"></div>
</div>
<script src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Function to handle file input change
$('#image-upload').on('change', function() {
var files = $(this)[0].files;
// Clear the existing previews
$('.image-preview').empty();
// Loop through selected files and display previews
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file.type.match('image.*')) {
var reader = new FileReader();
reader.onload = function(e) {
var img = $('<img>').attr('src', e.target.result);
$('.image-preview').append(img);
}
reader.readAsDataURL(file);
}
}
});
});
</script>
</body>
</html>
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides