stressed out
stressed out

Reputation: 552

Setting the value of a file input via JavaScript fires a seemingly irrelevant event

My actual code is very long (86 lines); so, I'll just write the structure of my code to avoid making this post very long:

$('#myFile').on('change', function(){
 if(test == "passed"){
 //blah blah blah, blah blah blah
    $('#modalButton').on('click', function(){
         //blah blah blah, blah blah blah
         $.ajax({
         url: "process.php",
         type: "POST",
         //blah blah blah, blah blah blah
         });
    });
 } else {
    document.getElementById("myFile").value = null;
 }
});

And I have a file input element with the name myFile on my page.

When a user selects a file, the change event is fired and the outermost block is supposed to run. Then I will test user's file (photo) by checking its size and type and if it passed the test, I will show a modal that allows the user to crop the selected photo by using croppie.js plugin. The crop button is called modalButton. After it's pressed, I will send user's cropped photo to my server using ajax to upload it on my server.

The thing is that when a user selects a photo that doesn't pass the test and then the next time they select another photo which passes the test, the passed photo is uploaded more than once which means that probably the ajax event is fired multiple times. I can't see why that should be the case because ajax should be run after modalButton has been clicked not after the change of the input file element. Am I missing something?

I'll be more than happy to share my code (JS and HTML) with you if it's necessary. But I don't know how to paste them here without making this post look terrifyingly long!

Upvotes: 1

Views: 48

Answers (1)

Taplar
Taplar

Reputation: 24965

This is happening because you are creating a click event inside the change event. Previously created click events will not be removed by creating a new one. This is why creating event handlers inside other event handlers should be avoided. You could do off('click') before you create the new click to see if that fixes it, but ideally you should not have that binding inside the other binding in the first place.

//example
$('#modalButton').off('click').on('click', function(){ ... });

Upvotes: 2

Related Questions