Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change event called when changing element value IE 11/Angular

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

like image 248
Valter Júnior Avatar asked Jun 13 '17 14:06

Valter Júnior


1 Answers

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
});
like image 86
Natan Camargos Avatar answered Sep 30 '22 07:09

Natan Camargos