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

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

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

问题

<div class="multiple-uploader" id="multiple-uploader">
    <div class="mup-msg">
        <span class="mup-main-msg">点击上传图片。</span>
        <span class="mup-msg" id="max-upload-number">上传最多10张图片</span>
        <span class="mup-msg">仅允许上传图像、PDF 和 PSD 文件</span>
    </div>
</div>

<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

<div class="multiple-uploader" id="multiple-uploader">
    <div class="mup-msg">
        <span class="mup-main-msg">click to upload images.</span>
        <span class="mup-msg" id="max-upload-number">Upload up to 10 images</span>
        <span class="mup-msg">Only images, pdf and psd files are allowed for upload</span>
    </div>
</div>

<button type="submit" id="btnSubmit" class="btn btn-primary  w-100">Save</button>

javascript

 class MultipleUploader {

    #multipleUploader;
    #$imagesUploadInput;

    constructor( multiUploaderSelector )
    {
        this.#multipleUploader   = document.querySelector(multiUploaderSelector);
        this.#$imagesUploadInput = document.createElement('input')
    }

    init( { maxUpload = 3 , maxSize = 1 , formSelector = 'form' , filesInpName = 'images'  } = {} )
    {

        const form = document.querySelector(formSelector);

        if (! this.#multipleUploader ) // check if the end user didnt write the multiple uploader div
            throw new Error('The multiple uploader element doesnt exist');

        if (! form ) // check if there is no form with this selector
            throw new Error('We couldn\'t find a form with this selector: ' + formSelector);

        // ensure that the form has enctype attribute with the value multipart/form-data
        form.enctype = 'multipart/form-data'

        if ( document.getElementById('max-upload-number') )
            document.getElementById('max-upload-number').innerHTML = `Upload up to ${ maxUpload } files`;


        // create multiple file input and make it hidden
        this.#$imagesUploadInput.type       = 'file';
        this.#$imagesUploadInput.name       = `${filesInpName}[]`;
        this.#$imagesUploadInput.multiple   = true;
        this.#$imagesUploadInput.accept     = "image";
        this.#$imagesUploadInput.class     = "image";

        this.#$imagesUploadInput.style.setProperty('display','none','important');
        // create multiple file input and make it hidden

        // append the newly created input to the form with the help of the formSelector provided by the user
        document.querySelector(formSelector).append( this.#$imagesUploadInput );

        this.#multipleUploader.addEventListener("click", (e) => {

            if ( e.target.className === 'multiple-uploader' || e.target.className === 'mup-msg' || e.target.className === 'mup-main-msg' )
                this.#$imagesUploadInput.click() // trigger the input file to upload images

        });

        const self = this;

        // preview the uploaded images
        this.#$imagesUploadInput.addEventListener("change",function () {

            if (this.files.length > 0)
            {

                self.#multipleUploader.querySelectorAll('.image-container').forEach( image => image.remove() ); // clear the previous rendered images
                self.#multipleUploader.querySelector('.mup-msg').style.setProperty('display', 'none'); // hide the hint texts inside drop zone

                // if the length of uploaded images greater than the images uploaded by the user, the maximum uploaded will be considered
                const uploadedImagesCount       = this.files.length > maxUpload ? maxUpload : this.files.length;
                const unAcceptableImagesIndices = [];

                for (let index = 0; index < uploadedImagesCount; index++) {

                const imageSize             = self.#bytesToSize( this.files[ index ].size );
                const isImageSizeAcceptable = self.#checkImageSize( index , imageSize , maxSize , 'MB' );


                // appended the newly created image to the multiple uploader
                self.#multipleUploader.innerHTML += `

                <div class="image-container" data-image-index="${ index }" id="mup-image-${ index }" data-acceptable-image="${ +isImageSizeAcceptable }" >
                    <div class="image-size"> ${ imageSize['size'] + ' ' + imageSize['unit'] } </div>
                    ${ !isImageSizeAcceptable ? `<div class="exceeded-size"> greater than ${ maxSize } MB </div>` : '' }
                    <img src="${ URL.createObjectURL( this.files[ index ]) }"  class="image-preview" alt="" />
                </div>`;

                if ( ! isImageSizeAcceptable )

                    unAcceptableImagesIndices.push( index )

                }

                unAcceptableImagesIndices.forEach( (index ) => self.#removeFileFromInput(index, false ))

            }

        });

        // event for deleting uploaded images
        document.addEventListener('click',function(e){

            if( e.target.className === 'image-container' ) // clicked on remove pseudo element
            {
                const imageIndex        = e.target.getAttribute(`data-image-index`)
                const imageIsAcceptable = e.target.getAttribute(`data-acceptable-image`)

                e.target.remove() // remove the html element from the dom

                if ( +imageIsAcceptable )
                    self.#removeFileFromInput(imageIndex)

                if ( document.querySelectorAll('.image-container').length === 0 ) // if there are no images
                    self.clear();


                self.#reorderFilesIndices(); // reorder images indices
            }

        });



        return this;

    }

    clear()
    {
        this.#multipleUploader.querySelectorAll('.image-container').forEach( image => image.remove() );
        this.#multipleUploader.querySelectorAll('.mup-msg').forEach( msg => msg.style.setProperty('display', 'flex') );
        this.#$imagesUploadInput.value = [];
    }

    #removeFileFromInput( deletedIndex )
    {
        // remove the delete file from input
        const dt = new DataTransfer()

        for (const [ index, file] of Object.entries( this.#$imagesUploadInput.files ))
        {
            if ( index != deletedIndex )
                dt.items.add( file )

        }

        this.#$imagesUploadInput.files = dt.files
        // remove the delete file from input

    }

    #reorderFilesIndices()
    {
        document.querySelectorAll('.image-container').forEach( ( element, index) => {
            element.setAttribute('data-image-index', index.toString() );
            element.setAttribute('id',`mup-image-${ index }`)
        });
    }

    #checkImageSize( imageIndex, imageSize , maxSize   )
    {
       return  imageSize['unit'] !== 'MB' || ( imageSize['unit'] === 'MB' && ( imageSize['size'] <= maxSize ) ) ; // return true if acceptable
    }

    #bytesToSize(bytes)
    {
        const sizes = ['Bytes', 'KB', 'MB']

        const i = parseInt( Math.floor(Math.log(bytes) / Math.log(1024) ), 10)

        if (i === 0)
            return {size: bytes , unit: sizes[i] }
        else
            return {size: (bytes / (1024 ** i)).toFixed(1) , unit: sizes[i] }

    }
}

答案1

得分: 1

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

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

if (this.files.length > 0)
{
  // 你当前的代码

  document.getElementById("btnSubmit").disabled = unAcceptableImagesIndices.length > 0;
}
英文:

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:

if (this.files.length > 0)
{
  // your current code

  document.getElementById("btnSubmit").disabled = unAcceptableImagesIndices.length > 0;
}

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:

确定