如何在 JavaScript 中设置最大限制

How to put maximum limit in a JavaScript?

本文关键字:设置 JavaScript      更新时间:2023-09-26

这是我的表单上传多张图片的部分。它有一个添加更多按钮,用于打开一个新的输入字段。每当用户单击"添加更多"按钮时,都会打开一个新的输入字段。但是,我希望在打开第 5 个输入字段后,并且用户再次单击添加更多,不应打开任何新字段(即我希望将输入字段的大小限制为 5)

<div id="formdiv">
    <form enctype="multipart/form-data" action="" method="post">
        <div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
            <input type="button" id="add_more" class="upload" value="Add More Files"/>
            <input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
    </form>
</div>

处理工作的 JavaScript

var abc = 0; //Declaring and defining global increment variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() {
        $(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),        
                $("<br/><br/>")
                ));
    });
//following function will executes on change event of file input to select different file   
$('body').on('change', '#file', function(){
            if (this.files && this.files[0]) {
                 abc += 1; //increementing global variable by 1
                
                var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
               
                var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);
               
                $(this).hide();
                $("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'img/x.png', alt: 'delete'}).click(function() {
                $(this).parent().parent().remove();
                }));
            }
        });
//To preview image     
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };
    $('#upload').click(function(e) {
        var name = $(":file").val();
        if (!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }
    });
});

谁能帮我应用这个最大限制?

您需要设置一个计数器来实现此目的。 您可以按如下方式更新代码。

var count=0;
  $('#add_more').click(function() {
if(count<5)
{
        $(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),        
                $("<br/><br/>")
                ));
count++;
 } 
  });