1

So what I want to achieve is an array containing x images, that once button click will randomly select one of the images and then put it inside a div with an id of 'image-placeholder'. On top of that I'd like to add an if statement that's going to check answers input accordingly to image source location/image index in the array (for example answer: C/c is valid only in case when source image of the given image within the array equals one.jpg)

What I've achieved so far is the following code, unfortunately enough I can't figure out how to form an if condition that'd include checking the image source code with the answer.

    //function creating images
    var createImage = function(src, title) {
        title = title.replace(/"/g, """);
        return '<img src="' + src + '" title="' + title + '" alt="' + title + '" />';
    }

    //array with images within
    var newArray = [];
    newArray.push(createImage("foo.jpg", "foo title"));
    newArray.push(createImage("doo.jpg", "doo title"));

    //function choosing random array picture
    function click() {
        var rand = newArray[Math.floor(Math.random() * newArray.length)];
        document.getElementById("image-placeholder").innerHTML = rand;
    }

    //function checking whenever answer matches the image source
    function check() {
        var answer = document.getElementById("answer").value;
        img = newArray[0];

        if (img == "<img src='foo.jpg' title='foo title' alt='foo title'/>" && answer == "C" || answer == "c") {
            window.alert("thats a good answer");
        } else {
            window.alert("that's a bad answer");
        }
    }

thanks for any sort of help

  • Please note that if `answer == "c"` then you will **always** get `true`, to fix it ==> `if ( img == "foo title" && (answer == "C" || answer == "c") ) {` – Alon Eitan Apr 29 '17 at 18:16
  • Oh, thank you very much but will it solve the issue with image source matching the answer? – Karl Friedrich Apr 29 '17 at 18:21
  • why do you store the whole image tag u can just store the image source !! – lotfio Apr 29 '17 at 18:24
  • @KarlFriedrich No, but please take a look at the duplicate question - It demonstrate how the get the `src` attribute of an image (But also you must change the condition to what I suggested in my first comment) – Alon Eitan Apr 29 '17 at 18:26

0 Answers0