Skip to content

Instantly share code, notes, and snippets.

@elvisciotti
Last active August 14, 2022 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elvisciotti/9661978 to your computer and use it in GitHub Desktop.
Save elvisciotti/9661978 to your computer and use it in GitHub Desktop.
Attach a "onchange" listener to file upload elements for each form. If the selected file size invalid (bigger than input.MAX_FILE_SIZE, disable submit button and append a message
$(document).ready(function() {
/*
* Attach a "onchange" listener to file upload elements for each form.
* Behaviour:
* If the selected file size invalid (bigger than the value from the <input name="MAX_FILE_SIZE" /> element):
* - disable submit button
* - append a message (class="errors") to the form.
* If the selected file size is valid:
* - enable the submit button
* - remove the error message previously added
*
* example of HTML form
* <form method="post" enctype="multipart/form-data" action="">
* <input type="hidden" name="MAX_FILE_SIZE" value="<26214400" />
* <input type="submit" value="Upload" />
* </form>
*/
$('body').on('change', 'input[type="file"]', function(e) {
// locate elements
var fileUploadElement = $(e.target);
var formElement = fileUploadElement.closest('form');
var inputMaxFileSize = formElement.find('input[name="MAX_FILE_SIZE"]');
var submitButton = formElement.find('input[type="submit"]');
var maxAllowedSize = parseFloat(inputMaxFileSize.val());
if (isNaN(maxAllowedSize)) {
return; // no validation
}
var selectedFileSize = parseFloat(this.files[0].size);
if (selectedFileSize > maxAllowedSize) {
formElement.append('<div class="errors" data-role="upload-error">The file you are trying to upload is '
+ Math.round(selectedFileSize / 1024 / 1024)
+ ' Mb.<br/>The maximum allowed size is '
+ Math.round(maxAllowedSize / 1024 / 1024)
+ ' Mb.</div>');
submitButton.attr('disabled', 'disabled');
} else {
submitButton.removeAttr('disabled');
formElement.find('[data-role="upload-error"]').remove();
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment