Fix my javascript - Image uploader

Job ID: 36986763

Budget: $10 – $30 USD

If I rearrange the images, it still uploads in the order initially chosen. For examples, 1.jpg and 2.jpg will upload as the first image 1.jgp and the second image as 2.jpg. If I rearrange so that 2.jpg is first, it still uploads 1.jpg first. Also if I remove an image, it still uploads the image. Here is the javascript. <script>
var files = []; // Global array to store the selected files in the order they were added

function previewImages() {
var previewDiv = $("#preview-images");
previewDiv.empty();

var selectedFiles = Array.from($("#images")[0].files); // Convert to a regular array
files.push(...selectedFiles); // Store selected files in the global array

for (let i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();

reader.onload = (function (file) {
return function (e) {
var img = $("<img>")
.attr("src", e.target.result)
.attr("alt", "Preview Image")
.addClass("img-fluid mb-2 draggable-image");

var removeBtn = $("<span>")
.addClass("remove")
.text("\u00D7") // Unicode for the "times" symbol
.click(function () {
// Get the corresponding file to be removed
var fileToRemove = file;
// Remove the image when the remove button is clicked
$(this).closest(".image-container").remove();
// Remove the file from the files array
files = files.filter(function (f) {
return f !== fileToRemove;
});
});

var imageContainer = $("<div>").addClass("image-container");
imageContainer.append(img).append(removeBtn);
previewDiv.append(imageContainer);
};
})(file);

reader.readAsDataURL(file);
}
}

// Call the previewImages function when files are selected
$("#images").on("change", previewImages);

// Enable Drag and Drop functionality using jQuery UI
$("#preview-images").sortable({
revert: true,
});
$("#preview-images").disableSelection();
</script>
Related categories: PHP JavaScript CSS HTML jQuery / Prototype