1

I need to make small app using html and JavaScript to search for image in given folder.

for example i have folder called /images with f1.jpg, f2.gif, f3.png images and html webpage with search input. when i search for f1 it should print the f1.jpg image with <img> tag bellow the search input.

How i can do that with html and javascript or ajax without print all images?

Html example code:

<!doctype html>
<html>
<head>
    <title>Search images</title>

<script type="text/javascript">
var folder = "images/";

$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                $("body").append( "<img src='"+ folder + val +"'>" );
            } 
        });
    }
});
</script>
</head>
<body>
<form>
<label>Search for image:</label>
<br />
<input type="text" name="search" placeholder="">
<button type="submit">Search</button>
<br />
<!-- Image result should appear here -->
</form>
</body>
</html>
Mahmoud Al-Nafei
  • 231
  • 6
  • 18

1 Answers1

0

you don't need ajax for this. you can just look if image is loaded or not using onload event of Image as shown below

var img = new Image();
img.src = path_to_image;

img.onerror = function() {
  // any logic in case of error
};

img.onload = function() {
  document.body.appendChild(img);
}; 

You can have a look at this example https://plnkr.co/edit/RWH73qp0jmOZeymvV6Aq?p=preview

Note: you can create your image url using predefined_path_to_folder + search_input_value and use it as value for img.src

S4beR
  • 1,872
  • 1
  • 17
  • 33
  • Yes, that could work if OP wants to play guess game with it's users: *enter an image name and hope we'll find it :)* Kidding. Not. But would be useful in any case to show a list of available images... just thinking loud... – Roko C. Buljan Mar 29 '16 at 23:30
  • user don't really need to guess. `onload` of page we should run a background script to find all available images using above code (assuming file name follows pattern like f1.png, f2.png, f3.png etc.) and then create a autocomplete for end user with that list. – S4beR Mar 30 '16 at 08:52