I have this JavaScript code which lets users upload and preview their uploaded images.
The images are being previewed through a table grid with specified dimensions.
My Question:
How can I edit the JavaScript to limit users from uploading more than 9 images?
Note: the same restriction would be implemented on the server side later on. Due to users being able to bypass this JavaScript code. But that's for later. For now I want to get the frontend to limit the users.
Note: This question has been asked before but was based solely on limiting file input button. My problem is implementing this code with mine.
Code in question (to limit file upload)
$(function() {
$("button[type = 'submit']").click(function(event) {
var $fileUpload = $("input[type='file']");
if (parseInt($fileUpload.get(0).files.length) > 10) {
alert("You are only allowed to upload a maximum of 10 files");
event.preventDefault();
}
});
});
(function (global) {
var imagesPerRow = 3,
chooseFiles,
columns,
previews;
function PreviewImages() {
var row;
Array.prototype.forEach.call(chooseFiles.files, function (file, index) {
var cindex = index % imagesPerRow,
oFReader = new FileReader(),
cell,
image;
if (cindex === 0) {
row = previews.insertRow(Math.ceil(index / imagesPerRow));
}
image = document.createElement("img");
image.id = "img_" + index;
image.style.objectFit = "cover";
image.style.width = "150px";
image.style.height = "90px";
cell = row.insertCell(cindex);
cell.appendChild(image);
oFReader.addEventListener("load", function assignImageSrc(evt) {
image.src = evt.target.result;
this.removeEventListener("load", assignImageSrc);
}, false);
oFReader.readAsDataURL(file);
});
}
global.addEventListener("load", function windowLoadHandler() {
global.removeEventListener("load", windowLoadHandler);
chooseFiles = document.getElementById("chooseFiles");
columns = document.getElementById("columns");
previews = document.getElementById("previews");
var row = columns.insertRow(-1),
header,
i;
for (i = 0; i < imagesPerRow; i += 1) {
header = row.insertCell(-1);
header.style.width = (100 / imagesPerRow) + "%";
}
chooseFiles.addEventListener("change", PreviewImages, false);
}, false);
}(window));
div.rounded {
width: 100%;
border-style: solid;
border-width: 1px;
border-radius: 5px;
}
label {
display: block;
}
input {
display: block;
}
#previewTable {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="imagesDiv" class="rounded">
<label for="chooseFiles">Add Images</label>
<input type="file" id="chooseFiles" multiple="multiple" />
<table id="previewTable">
<thead id="columns"></thead>
<tbody id="previews"></tbody>
</table>
</div>