当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Validation to restrict user form uploading heavy files

问题描述:

Hi I am using this code to restrict user from uploading the heavy files above 5mb. But this is only working for first file filed not for the rest of file fileds.

var n=1;

$(document).ready(function()

{

$('.add_field').click(function(){

if(n < 5)

{

n=n+1;

var newid="file"+n;

var input = $('#file1');

var clone = input.clone(true);

//clone.removeAttr ('id');

clone.attr('title','file'+n);

clone.attr('id','file'+n);

clone.val('');

clone.appendTo('.input_holder');}

});

$('.remove_field').click(function(){

if(n!=1)

{

n=n-1;

if($('.input_holder input:last-child').attr('id') != 'input_clone'){

$('.input_holder input:last-child').remove();

}

}

});

$("#file1").change(function ()

{

var iSize = ($("#file1")[0].files[0].size / 1024);

if(iSize>5000)

{

alert("Too Large FIle");

example_reset_html('file1d');

}

});

$("#file2").change(function ()

{

var iSize = ($("#file2")[0].files[0].size / 1024);

if(iSize>5000)

{

alert("Too Large FIle");

example_reset_html('file1d');

}

});

});

function example_reset_html(id) {

$('#'+id).html($('#'+id).html());

}

I checked this all browser and tried hacks but it seems that something is wrong and not working properly.

网友答案:

Can you bind your event on $('.input_holder')? It seems that element holds all file inputs so you only have to bind the change event to their parent.

$(".input_holder").change(function (e) 
    {   
        if(e.target.type==="file"){
          var iSize = (e.target.files[0].size / 1024);
          if(iSize>5000)
          {
              alert("Too Large FIle");
              example_reset_html(e.target.id);
          }
        }
}); 
分享给朋友:
您可能感兴趣的文章:
随机阅读: