0

I have a small piece of JavaScript that changes an image based on a drop down. It currently works and changes the image as it should. Unfortunately if the image is not there it shows the missing image icon and I'd rather it kept the default image.

My JavaScript is -

<script>
$(function() {
    $("#input_1").change(function(){
        var selectedImage = $(this).find(':selected').val();
        val = $("#input_1 option:selected").text();
        $("a.lb:first").html( "<img src=images/11_" + selectedImage + ".jpg>");
        $('a.lb:first img').addClass( "img-fluid" );

    });
});
</script>

My HTML is -

<img src="images/11_1.jpg" alt="Objective Marker Bases" title="Objective Marker Bases" class="img-fluid">
<select name="id[1]" required="required" aria-required="true" id="input_1" class="form-control">
<option value="" selected="selected">--- Please Select ---</option>
<option value="1">White</option>
<option value="2">Yellow (+£1.00)</option>
<option value="4">Blue</option>
</select>
j08691
  • 204,283
  • 31
  • 260
  • 272
Foster
  • 23
  • 7
  • Test the URL is valid before switching it. E.g. see https://stackoverflow.com/questions/9815762/detect-when-an-image-fails-to-load-in-javascript – Chase Jun 08 '20 at 20:09

1 Answers1

0

You can put an event listener on your image.

$('a.lb:first img').on('error', function(){
   $(this).attr('src', 'images/11_1.jpg'); // default image
});
Joel'-'
  • 652
  • 1
  • 5
  • 17