progr
progr

Reputation: 31

How to check if input file is empty in jquery without using another button

I want to detect if an image has been selected. If so, then display some text otherwise if its empty display some other text. As soon as the image is selected, automatically different message should be shown not after clicking a button. The following is my code.

Html

<input type="file" name="picture" id="image" />
<div id="message">Add image</div>

Javascript

$(document).ready(
 if ($('#image').get(0).files.length !== 0) {
  function() {
    $('#message').text('You added an image');
   }
 }
);

Upvotes: 0

Views: 1770

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

You can set a listener on the input and change the content of message as follows:

$( document ).ready(function(){
     $('#image').on('change', function(){
          $('#message').html('You selected an image');
     });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="picture" id="image" />
<div id="message">Add image</div>

Upvotes: 1

Related Questions