我想使用JavaScript禁用按钮,如果任何图像大于1MB。

huangapple go评论95阅读模式
英文:

I want to disable button if any image greater then one mb using javascript

问题

  1. <div class="multiple-uploader" id="multiple-uploader">
  2. <div class="mup-msg">
  3. <span class="mup-main-msg">点击上传图片。</span>
  4. <span class="mup-msg" id="max-upload-number">上传最多10张图片</span>
  5. <span class="mup-msg">仅允许上传图像、PDF PSD 文件</span>
  6. </div>
  7. </div>
  8. <button type="submit" id="btnSubmit" class="btn btn-primary w-100">保存</button>
英文:

I am beginner with javascript and I am using this plugin for uploading multiple image https://www.cssscript.com/demo/multiple-image-uploader/ and just i want to disable button if any image is greater then one mb the button should be disabled Does anyone khow where i need to put this code $('#btnSubmit').prop('disabled', true); please help me ? thank u.

我想使用JavaScript禁用按钮,如果任何图像大于1MB。

html view

  1. <div class="multiple-uploader" id="multiple-uploader">
  2. <div class="mup-msg">
  3. <span class="mup-main-msg">click to upload images.</span>
  4. <span class="mup-msg" id="max-upload-number">Upload up to 10 images</span>
  5. <span class="mup-msg">Only images, pdf and psd files are allowed for upload</span>
  6. </div>
  7. </div>
  8. <button type="submit" id="btnSubmit" class="btn btn-primary w-100">Save</button>

javascript

  1. class MultipleUploader {
  2. #multipleUploader;
  3. #$imagesUploadInput;
  4. constructor( multiUploaderSelector )
  5. {
  6. this.#multipleUploader = document.querySelector(multiUploaderSelector);
  7. this.#$imagesUploadInput = document.createElement('input')
  8. }
  9. init( { maxUpload = 3 , maxSize = 1 , formSelector = 'form' , filesInpName = 'images' } = {} )
  10. {
  11. const form = document.querySelector(formSelector);
  12. if (! this.#multipleUploader ) // check if the end user didnt write the multiple uploader div
  13. throw new Error('The multiple uploader element doesnt exist');
  14. if (! form ) // check if there is no form with this selector
  15. throw new Error('We couldn\'t find a form with this selector: ' + formSelector);
  16. // ensure that the form has enctype attribute with the value multipart/form-data
  17. form.enctype = 'multipart/form-data'
  18. if ( document.getElementById('max-upload-number') )
  19. document.getElementById('max-upload-number').innerHTML = `Upload up to ${ maxUpload } files`;
  20. // create multiple file input and make it hidden
  21. this.#$imagesUploadInput.type = 'file';
  22. this.#$imagesUploadInput.name = `${filesInpName}[]`;
  23. this.#$imagesUploadInput.multiple = true;
  24. this.#$imagesUploadInput.accept = "image";
  25. this.#$imagesUploadInput.class = "image";
  26. this.#$imagesUploadInput.style.setProperty('display','none','important');
  27. // create multiple file input and make it hidden
  28. // append the newly created input to the form with the help of the formSelector provided by the user
  29. document.querySelector(formSelector).append( this.#$imagesUploadInput );
  30. this.#multipleUploader.addEventListener("click", (e) => {
  31. if ( e.target.className === 'multiple-uploader' || e.target.className === 'mup-msg' || e.target.className === 'mup-main-msg' )
  32. this.#$imagesUploadInput.click() // trigger the input file to upload images
  33. });
  34. const self = this;
  35. // preview the uploaded images
  36. this.#$imagesUploadInput.addEventListener("change",function () {
  37. if (this.files.length > 0)
  38. {
  39. self.#multipleUploader.querySelectorAll('.image-container').forEach( image => image.remove() ); // clear the previous rendered images
  40. self.#multipleUploader.querySelector('.mup-msg').style.setProperty('display', 'none'); // hide the hint texts inside drop zone
  41. // if the length of uploaded images greater than the images uploaded by the user, the maximum uploaded will be considered
  42. const uploadedImagesCount = this.files.length > maxUpload ? maxUpload : this.files.length;
  43. const unAcceptableImagesIndices = [];
  44. for (let index = 0; index < uploadedImagesCount; index++) {
  45. const imageSize = self.#bytesToSize( this.files[ index ].size );
  46. const isImageSizeAcceptable = self.#checkImageSize( index , imageSize , maxSize , 'MB' );
  47. // appended the newly created image to the multiple uploader
  48. self.#multipleUploader.innerHTML += `
  49. <div class="image-container" data-image-index="${ index }" id="mup-image-${ index }" data-acceptable-image="${ +isImageSizeAcceptable }" >
  50. <div class="image-size"> ${ imageSize['size'] + ' ' + imageSize['unit'] } </div>
  51. ${ !isImageSizeAcceptable ? `<div class="exceeded-size"> greater than ${ maxSize } MB </div>` : '' }
  52. <img src="${ URL.createObjectURL( this.files[ index ]) }" class="image-preview" alt="" />
  53. </div>`;
  54. if ( ! isImageSizeAcceptable )
  55. unAcceptableImagesIndices.push( index )
  56. }
  57. unAcceptableImagesIndices.forEach( (index ) => self.#removeFileFromInput(index, false ))
  58. }
  59. });
  60. // event for deleting uploaded images
  61. document.addEventListener('click',function(e){
  62. if( e.target.className === 'image-container' ) // clicked on remove pseudo element
  63. {
  64. const imageIndex = e.target.getAttribute(`data-image-index`)
  65. const imageIsAcceptable = e.target.getAttribute(`data-acceptable-image`)
  66. e.target.remove() // remove the html element from the dom
  67. if ( +imageIsAcceptable )
  68. self.#removeFileFromInput(imageIndex)
  69. if ( document.querySelectorAll('.image-container').length === 0 ) // if there are no images
  70. self.clear();
  71. self.#reorderFilesIndices(); // reorder images indices
  72. }
  73. });
  74. return this;
  75. }
  76. clear()
  77. {
  78. this.#multipleUploader.querySelectorAll('.image-container').forEach( image => image.remove() );
  79. this.#multipleUploader.querySelectorAll('.mup-msg').forEach( msg => msg.style.setProperty('display', 'flex') );
  80. this.#$imagesUploadInput.value = [];
  81. }
  82. #removeFileFromInput( deletedIndex )
  83. {
  84. // remove the delete file from input
  85. const dt = new DataTransfer()
  86. for (const [ index, file] of Object.entries( this.#$imagesUploadInput.files ))
  87. {
  88. if ( index != deletedIndex )
  89. dt.items.add( file )
  90. }
  91. this.#$imagesUploadInput.files = dt.files
  92. // remove the delete file from input
  93. }
  94. #reorderFilesIndices()
  95. {
  96. document.querySelectorAll('.image-container').forEach( ( element, index) => {
  97. element.setAttribute('data-image-index', index.toString() );
  98. element.setAttribute('id',`mup-image-${ index }`)
  99. });
  100. }
  101. #checkImageSize( imageIndex, imageSize , maxSize )
  102. {
  103. return imageSize['unit'] !== 'MB' || ( imageSize['unit'] === 'MB' && ( imageSize['size'] <= maxSize ) ) ; // return true if acceptable
  104. }
  105. #bytesToSize(bytes)
  106. {
  107. const sizes = ['Bytes', 'KB', 'MB']
  108. const i = parseInt( Math.floor(Math.log(bytes) / Math.log(1024) ), 10)
  109. if (i === 0)
  110. return {size: bytes , unit: sizes[i] }
  111. else
  112. return {size: (bytes / (1024 ** i)).toFixed(1) , unit: sizes[i] }
  113. }
  114. }

答案1

得分: 1

你的代码已经包含了所需的所有信息。你有一个包含不可接受图片索引的 unAcceptableImagesIndices 列表。

因此,你只需检查 unAcceptableImagesIndices 的长度是否不为零,如果是,则禁用按钮。例如,可以这样做:

  1. if (this.files.length > 0)
  2. {
  3. // 你当前的代码
  4. document.getElementById("btnSubmit").disabled = unAcceptableImagesIndices.length > 0;
  5. }
英文:

Your code already has all the information needed. You have unAcceptableImagesIndices that contains a list of unaccepted images.

So, all you need is just check if unAcceptableImagesIndices length is not zero and disable the button if so.
For example with something like this:

  1. if (this.files.length > 0)
  2. {
  3. // your current code
  4. document.getElementById("btnSubmit").disabled = unAcceptableImagesIndices.length > 0;
  5. }

huangapple
  • 本文由 发表于 2023年2月19日 16:37:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定