Last active
March 21, 2023 20:43
-
-
Save vandorjw/9cd722d81c20b23bf23d6d86f6197584 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//ensure we instantiate the listeneres on page-load. | |
window.addEventListener("DOMContentLoaded", AddFileEventListeners); | |
// add-form.formset is a custom event that is only 'emitted' by the formset.js file | |
// When new forms are added to the page, we need those forms to also have an event listener | |
// not just the ones that were present on page load. | |
document.querySelector('form').addEventListener("add-form.formset", AddFileEventListeners); | |
function AddFileEventListeners() { | |
console.log('adding evt listeners'); | |
// grabs all html elements on the page with attribute type=file | |
let fileInputs = document.querySelectorAll('[type=file]'); | |
// loop over all of them, and give them an event listener for 'change' event | |
fileInputs.forEach(inputField => { | |
// remove eventListeners so we don't duplicate work done over and over. | |
inputField.removeEventListener("change", validateFileSize) | |
// add the eventListeners back to all fileInputs | |
inputField.addEventListener("change", validateFileSize) | |
}) | |
function validateFileSize(evt) { | |
for (const file of event.target.files) { | |
// do validation work here | |
// https://developer.mozilla.org/en-US/docs/Web/API/Blob/size | |
console.log(`${file.name} has a size of ${file.size} bytes.\n`); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment