Search code examples
javascriptphparraysimagesource

show the image with specific named using javascript


I have some picture in folder "../../images"

I give the name of picture with example

101_2018_1_1.jpg

101_2018_1_2.jpg

101_2018_1_3.jpg

101 is on var1

2018 is on id year

and 1 is on var3

and the last is auto increment

how can I call all the images with specific named based on combo box I chose with javascript and show the image on my page?

here the example of my form

<form>
<select name="var1" id="var1" >
	<option value='101'>id 1</option>
	<option value='102'>id 2</option>
	<option value='103'>id 3</option>
</select>

<input type="text"  id="year" name="year" value="<?php echo date('Y'); ?>">

<select name="var3" id="var3" >
	<option value='1'>case 1</option>
	<option value='2'>case 2</option>
	<option value='3'>case 3</option>
	<option value='4'>case 4</option>
</select>

<button  type="submit" name="search">search</button>
</form>


Solution

  • Using jQuery you can do something like:

    $(document).ready(function() {
      $("form").submit(function(e) {
        e.preventDefault();
    
        var URL = "www.example.com/image/";
    
        //Get the values of form element 
        var var1 = $("#var1").val();
        var year = $("#year").val();
        var var3 = $("#var3").val();
    
        //Check Up to 10 increments
        for (i = 1; i <= 10; i++) {
          var img = URL + var1 + "_" + year + "_" + var3 + "_" + i + ".jpg";
          getImage(img);
        }
    
        return false;
      });
    });
    
    /*
      Check if image exist and add it.
      If not, just console
    */
    function getImage(image_url) {
      $.get(image_url)
        .done(function() {
          // Image does exist - append on #image-container container
          $("#image-container").append('<img src="' + image_url + '">');
        }).fail(function() {
          // Image doesn't exist - do nothing.
          console.log(image_url + " does not exist.");
        });
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
      <select name="var1" id="var1">
    				<option value='101'>id 1</option>
    				<option value='102'>id 2</option>
    				<option value='103'>id 3</option>
       </select>
    
      <input type="text" id="year" name="year" value="2018">
    
      <select name="var3" id="var3">
    				<option value='1'>case 1</option>
    				<option value='2'>case 2</option>
    				<option value='3'>case 3</option>
    				<option value='4'>case 4</option>
      </select>
    
      <div id="image-container"> </div>
    
      <button type="submit" name="search">search</button>
    </form>