keyboardwarrior
keyboardwarrior

Reputation: 35

jQuery Test if image has this extension else try the next

I've got a dropdown box with a bunch of options for an image. Each image has an id in the database. The images are located in foo/images/ and are named after their id's in the database (21.gif, 32.png etc). The problem I'm having is testing to see if which extension works and use that one. Here's my code so far, i recently added the $.get(lnk) portion as a bad attempt, I'm new to Jquery. My thought process is if it was the right extension it would return true and be fine, and if it failed have it repeat until it returned true. Any way to do this? explain like im five

    <SELECT NAME=IMG1 onchange=\'
  this.form.SIGN_NFPA.selectedIndex = 0;
  var id = this.options[this.selectedIndex].value
  var exts = ["png", "gif", "jpg", "jpeg"];
  var count = 0;
  var lnk = (id) ? "foo/images/"+id+"."+exts[count] : "blank.gif";
  window.document.IMG1.src = lnk;
  $.get(lnk)
    .done(function() {
      return true;
      }).fail(function() {
      count = count + 1;
      lnk = (id) ? "foo/images/"+id+"."+exts[count] : "blank.gif";
      })
  return true;
\'>

Upvotes: 1

Views: 61

Answers (1)

Damion
Damion

Reputation: 49

I've commented the code to help make it more readable.

$( "#select" ).on( "change", function () {
    // grab the value for the select box
    var val = $( this ).val();
    // file extensions
    var exts = [ "gif", "png", "jpg", "jpeg" ];
    // set img = false, used to detect if img exists.
    var img = false;
    // set i = 0, stops the while looping forever
    var i = 0;

    var url;

    // while image is false and there are more extensions to try
    while ( !img && i < exts.length ) {
        // set the url
        url = "foo/images/" + val + "." + exts[ i ];
        // build and send a request to see i the image exists.
        var req = new XMLHttpRequest();
        req.open( 'GET', url, false );
        req.send();
        // set img to the request status
        img = req.status == 200;
        // add 1 to i
        i++;
    }
    // if no url, set url to "blank.gif"
    url = img ? url : "blank.gif";

    // set the image src attribute.
    $( "#" + val ).attr( "src", url );
} );

I hope this helps.

Upvotes: 2

Related Questions