4

I am using trigger('click') while using the file upload in jQuery. I am providing my code below.

$(document).on('click', '.browse', function(){
   var file = $(this).parent().parent().parent().find('.file');
   file.trigger('click');
   console.log('header');
 })

My html part is given below.

<div class="form-group" style="margin-bottom:0px;">
<input type="file" name="logoimage" id="logoimage" ng-model= "form.logoimage" onchange="angular.element(this).scope().uploadedImage(this);" accept=".gif,.jpg,.jpeg,.png" class="file">
<div class="input-group col-xs-12">
<input type="text" class="form-control" placeholder="Upload Logo" name="setlogoimage" id="setlogoimage" ng-model="setlogoimage">
<span class="input-group-btn">
<button class="browse btn btn-primary" type="button">Upload File</button></span> 
    </div>
</div>

If I am clicking on file input the above function is executing 3/2 times and I can know it from the console messages. At one time click header is coming 3 times as result I have to click on open button after selecting file from discs also 3 times. Here I need to execute at once at one time click.

8
  • 1
    This is because you bind multiple click events. Commented Dec 19, 2017 at 12:58
  • You want to prevent event propagation after triggering a click on the file Commented Dec 19, 2017 at 12:58
  • Can you just help me to do this for this scenario ? Commented Dec 19, 2017 at 13:00
  • @Satpal : Yes, there are many input type=file in a single page whose class name is .file but its working sometimes and max times this scenarioa. Commented Dec 19, 2017 at 13:04
  • @Satpal : when I am checking the length its give the error Uncaught TypeError: Cannot read property 'length' of undefined. Commented Dec 19, 2017 at 13:19

1 Answer 1

0

As your click event is getting binded multiple times you can use off('click')

$('.browse').off('click').on('click', function(){
  var file = $(this).parent().parent().parent().find('.file');
  file.trigger('click');
  console.log('header');
});
Sign up to request clarification or add additional context in comments.

3 Comments

I did as per you but other click events are blocking while I am using this.
Can you please try the above-edited changes as now you will bind the click event on the browser class thus the other events wont get effected
I did as per you but the file browsing is not working at all.

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.