1

i have this script in my html code

 <script typre="text/javascript">
        var img = new Array();
        img[0] = new Image();
        img[0].src = "../images/poggiatesta2.jpg";
        img[1] = new Image();
        img[1].src = "../images/poggiatesta1.JPG";
        for (var i = 0; i < img.length; i++) {
            var imagetag = document.createElement("img");
            var onclick = document.createAttribute("onclick");
            onclick.value = "myfun("+i+")";

            var sorc = document.createAttribute("src");
            sorc.value = img[i].src;

            var id = document.createAttribute("id");
            id.value = "my_image" + i;

            var clas = document.createAttribute("class");
            clas.value = "my_image_clas";

            imagetag.setAttributeNode(clas);
            imagetag.setAttributeNode(onclick);
            imagetag.setAttributeNode(sorc);
            imagetag.setAttributeNode(id);
            document.body.appendChild(imagetag);
        };
        function myfun(i) {
            var src1 = document.getElementById('my_image' + i).src;
            alert(src1);

        }
        </script>

It allows me to store the src of a selected image in a var. Now im trying to do a check, which means an alert message that pops out if i didnt select any images like this:

 function controllo() {

    if ((src1 == "") || (src1 == "undefined")) {
        alert("Select an image.");
    }
    else {
        location.href = "schienale.html";
    }
}

Here's the problem, src1 is a local var, how can i retrieve its data in order to complete my check funcion?

Francesco Monti
  • 151
  • 2
  • 10

1 Answers1

1

You could store src1 as a global (it is better to use a namespace, but for the sake of this question a global will do)

<script typre="text/javascript">
    var src1; //Notice i've declared the variable here.
    var img = new Array();
    img[0] = new Image();
    img[0].src = "../images/poggiatesta2.jpg";
    ...

Then in myFunc do:

function myfun(i) {
     src1 = document.getElementById('my_image' + i).src;
     alert(src1);
}

This will make src1 available everywhere.

Or, if possible, pass src1 into your controllo function. This is the preferred method because it prevents cluttering the global namespace, but will require the code to be changed elsewhere. This might help give you a hint though:

controllo(src1)    

function controllo(src1) {

if ((src1 == "") || (src1 == "undefined")) {
        alert("Select an image.");
    }
    else {
        location.href = "schienale.html";
    }
}
Community
  • 1
  • 1
Matt Lishman
  • 1,817
  • 2
  • 22
  • 34