Event on('change') fires by clicking outside the element

Asked

Viewed 790 times

3

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

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

It works almost straight, when I click off the input he gives the alert again and this should not occur, should give the alert only when I choose an image.

  • What is the input-imagem? a select? Already now missing a # or . here : $('input-imagem')

  • He put @Sergio is type file !!!

1 answer

2

Do so:

Missed you to define . for class or # to the id of the type element input file

<input type="file" name="input-imagem" id="input-imagem" >

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

Example: fiddle

or

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

Example: fiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.