Tom Tom - 1 year ago 110
jQuery Question

Getting Image Preview jQuery

I am trying to implement a simple jquery function which basically takes a HTML link and show an image preview however I cannot seem to get it working.

I have used JSFiddle - - to show what I'm trying to do with code

$('.test').blur(function() {

var src = jQuery(this).val();
var prevImg = jQuery('#prev > [id^="prevMe-"]').length;

if (src == null || src == undefined) {
//trying to remove image if it's the same value or input is emptied
jQuery('#prevMe-' + (prevImg - 1)).remove();
} else {
jQuery('#prev').append('<img id="prevMe-' + prevImg + '" style="max-width:50px;" src="' + src + '">');

I am trying to:

  1. Remove the preview image if the input link is removed

  2. Show the preview image if input is there

  3. Validate it's an image [gif,jpg,png]

Can anyone assist ?

Answer Source

Your implementation works to a point, I've had a go at changing it to do a little more of what you hoped for. Hope it helps.

$('.test').blur(function() {

var src = jQuery(this).val();
var LinkedImage = $(this).data('linkedImage');

if(!src.match("http:\/\/.*\/(.*)\.(jpg|jpeg|png|gif)") && src != "")
     $("#warning").html("Must be an image");
      return false;  
} else {

if (src != "") {
   $('#prev').append('<img class="previewImage" style="max-width:50px;" src="' + src + '">');
   $(this).data('linkedImage', $('img:last' ,'#prev'));      


<input id="0" type="text" class="test" />
<input id="1" type="text" class="test"/>
<input id="3" type="text" class="test"/>

<div id="warning"></div>
<div id="prev"></div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download