0

I am having a file upload form where I am checking the file size through javascript before finally submitting the form. The form is working fine and when I try to upload a file more than the mentioned size then it shows the correct alert at the first time. But if I again click on upload without selecting another file I get the same alert twice. If I again repeat the process I get the alert 3 times. Below is the code

<script>    
var flag=0;
$('#filename').bind('change', function() { 
var filesiz =  this.files[0].size;
if (filesiz >10485760)
{flag=1;}
else 
{flag=0;}
});

function upfunc(){
  $('#smalldata').hide();
  $('#invalidfile').hide();
  $('#invalidfile9').hide();
  if($( "#UserComments" ).hasClass( "textAreaField valid" ) && $( "#filename" ).hasClass( "valid" )){
  $('#loading_image').show(); // show animation
  $( "#uploadsfrm" ).submit(function() {
  if(flag==1)
  {alert ('File size cannot exceed 10 MB.');
  $('#loading_image').hide();
  return false;
  //event.preventDefault();
  }
  else
  return true;
  });
  }
 }
</script>

I think the error may be because I am using bind. Any help would be really appreciated.Thank you

8
  • If you're not selecting another file, the same file is still selected, so why would you expect a different result ? Commented Dec 23, 2013 at 12:42
  • But I am not able to understand as to why the second time I am getting the alert two times and then the third time the alert increases to three. Also how can I overcome this problem? Commented Dec 23, 2013 at 12:57
  • That's because you placed the event handler inside a function, and everytime upfunc() runs, a new event handler is added, and another alert pops up, making two, then three etc. Commented Dec 23, 2013 at 13:00
  • So can you please guide me in the right direction as I am not that proficient. Commented Dec 23, 2013 at 13:03
  • I'm sorry, but I have no idea where you are calling upfunc() ? Commented Dec 23, 2013 at 13:05

1 Answer 1

2

You have a multi event calling in here. Every time you call upfunc() you attach a Submit event. you might consider either declaring Submit event once or use $( "#uploadsfrm" ).unbind('submit') before the $( "#uploadsfrm" ).submit(function()....

so in fact, first call you will have 1 event listener, 2nd call you will attach another event, which now sums up to 2..there until infinite. e.preventProgration or StopDefault wont help because its the same object and therefor it wont stop the calling of the events. Even if it will help, it is just a piece of bad code :(

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Unbind function did the trick. Now its working absolutely fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.