0

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');
   }
 }
);
3
  • You can use select with predefined images and monitor with jQuery any change in selected item. Commented Jun 8, 2020 at 20:16
  • You execute your jQuery when the DOM loads so the file input won't ever have a length, nor will that code execute when the file input changes Commented Jun 8, 2020 at 20:16
  • This is very strangely structured. It seems like you took the function(){} that should be there for the document ready, and moved it down into your if statement. Commented Jun 8, 2020 at 20:17

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.