mistery_girl mistery_girl - 2 months ago 11
Javascript Question

Two input fields with the same name - on change event

I have 2 input fields with the same name - that is because business logic of the project.

They look like that:



<input type="file" name="director_front_passport[]" class="app-file" id="director_front_passport" />
<input type="file" name="director_front_passport[]" class="app-file" />





I need to append image name after input field on change event.But in this way, how to make difference between these 2 inputs?

I thought to try to differ them by
id
attr, but I have
clone
button to add more fields and I don't think this will work on change event.

Updated: My code for on change event is the following:



var inputs = document.querySelectorAll( '.app-file' );
Array.prototype.forEach.call( inputs, function( input )
{
input.addEventListener( 'change', function( e )
{
//my code for displaying image
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>





I updated my code using
$(this)
to find changed input and my code looks:



var inputs = document.querySelectorAll( '.app-file' );

Array.prototype.forEach.call( inputs, function( input )
{
input.addEventListener( 'change', function( e )
{
var changed = $(this);
var label = changed.next(),
labelVal = label.innerHTML,
divName = label.next();
fileName = e.target.value.split('\\').pop();
divName.html(fileName);

});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="file" name="director_front_passport[]" class="app-file" id="director_front_passport" />
<input type="file" name="director_front_passport[]" class="app-file" />




Answer

You can use the this keyword within the event handler to identify the element which raised the event. Try this:

$('.app-file').change(function() {
  $(this).after('<div>' + this.files[0].name + '</div>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="director_front_passport[]" class="app-file" id="director_front_passport" />
<input type="file" name="director_front_passport[]" class="app-file" />

With your second example it's a little odd to call forEach in the manner you are. You can just call forEach on the nodeList returned from querySelectorAll, like this:

document.querySelectorAll('.app-file').forEach(function(input) {
    input.addEventListener('change', function(e) {
        // my code for displaying image
    })
}
Comments