On event ('change') triggers when clicking outside the element

3

I have the following code in a input of type file :

$('input-imagem').on('change', function() {
   alert( $(this).val()); 
});

It works almost right, when I click out of input it gives alert again and this should not occur, it should give alert only when I choose an image.

    
asked by anonymous 18.06.2014 / 16:23

1 answer

2

Do so:

class or # id element of type input file

<input type="file" name="input-imagem" id="input-imagem" >
$('#input-imagem').change(function() {
   if ($(this).val() != ""){
      alert($(this).val()); 
   }
});

Example: fiddle a>

or

$('#input-imagem').on('change', function() {
    if ($(this).val() != ""){
       alert( $(this).val());
    }
});

Example: fiddle a>

    
18.06.2014 / 16:28