9

I've created an directive to work with files. When I change the file or select a new one I call this code:

element.val('');

I'm doing this to be able to remove the selected file and select the same after that. If I don't do this, when I delete the selected file and select the same again, then the change event won't be called and I can't do what I need to do.

I just need to know if there is a way of avoid IE to call the change event when I change the value of the input.

I searched a little bit and found comments like this:

The onchange event on textboxes and textarea elements only fires when the element loses focus, and if its value is now other than its value when it got focus.

So, this change event was not supposed to be called when I just change de value programatically.

Any ideas?

EDIT:

I've created a jsfiddle with the behaviour

0

1 Answer 1

6

It seems that element.val('') emit a new change event, causing multiple calls to your listener. That said, you can avoid this weird behavior by checking the input value like the following:

element.bind('change', function(){
    if(!element.val()) {
      return;
    }
    element.val('');
    // code goes here
});
1
  • element.bind is deprecated, instead this use on(). Commented Jun 13, 2017 at 18:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.