0

I have the following code in my html file:

<form enctype="multipart/form-data" class="form1" name="form1">
    <input type="button" id="button1" class="button1" value="Update 1"/>
    <input name="archivo1" type="file" class="archivo1" id="archivo1" />
</form>
<form enctype="multipart/form-data" class="form2">
    <input type="button" id="button2" class="button2" value="Update 2"/>
    <input name="archivo2" type="file" class="archivo2" id="archivo2" />
</form>

So, I want to detect automatically any change of any file and make different actions depending on the file selected. If I use

$(':file').change(function()
{
    //Code here
}

I want to know if I select the file named as archivo1 or the file named as archivo2. Any suggestions?

Regards!

2 Answers 2

2

I want to detect automatically any change of any file and make different actions depending on the file selected

In that case I would give them the same class (or use your original $(":file")...) and test the ID or name

$(function() {
  $(".archivo").on("change",function() { 
   if (this.id == "archivo1") { ... // or this.name =="archivo1"
   }
   else if (this.id == "archivo2") { ... // or this.name =="archivo2"
   }
 });  
});

You can also look at the parent or the nearest form:

if ($(this).parent.attr("name")=="form1"

or

if ($(this).closest("form").attr("name")=="form1"
Sign up to request clarification or add additional context in comments.

3 Comments

This one is much better given the fact that it puts the related code in one place by using if conditions.
I agree this is best suited. But what if there's no id.
Then your code would also not work? I could change to if ($(this).parent.attr("name")=="form1" too if needed
1

You can use attribute equals selector like this:

$('input[type="file"][name="archivo1"]').change(function()
{
    //Code here
});

But since you're using id then you can use use that id as IDs are unique in the page.

$('#archivo1').change(function()
    {
        //Code here
    });

Updated as per notice as you need one change function to detect all particular file.

$(':file').change(function()
{
 if ($(this).attr('name')=='archivo1') {
    // ...
 }
//do check like above ...
});

1 Comment

My guess is this .[for downvote (I didnt do the downvote) ].. The question was "how to detect change for every file change" but your answer detects changes for a particular file type input.

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.