2

Why Iam unable to change the image source? here is my code

<script>
function changeImage() {
var image = document.getElementById("myImgId");
if (image.src.match("C:\Users\USER\Desktop\GRAPHICS\photo2.jpg")) {
    image.src="C:\Users\USER\Desktop\GRAPHICS\photo3.jpg";
} else {
    image.src="C:\Users\USER\Desktop\GRAPHICS\photo1.jpg";
}
}
</script>
  • Possible duplicate of [JavaScript: Changing src-attribute of a embed-tag](http://stackoverflow.com/questions/2493706/javascript-changing-src-attribute-of-a-embed-tag) – AleFranz Feb 15 '16 at 09:35
  • As said already, try to escape your backslashes with another backslash like: "C:\\Users\\USER\\Desktop\\GRAPHICS\\photo3.jpg"; – Fearodin Feb 15 '16 at 09:38

1 Answers1

5

Three reasons:

  1. Because \ in JavaScript strings (as in my programming languages) is an escape character, so your string doesn't actually have any backslashes in it.

    To have an actual backslash in a string literal, you need to escape it — with a backslash.

  2. The src property is a fully-resolved URL, which will start with a protocol, in this case file:, and have normalized slashes (backslashes become / in normalized URLs).

  3. String#match expects a regular expression. You're passing it a string, and so the string will be run through new RegExp, which means that even with \\, you still won't have backslashes in that regex because backslash is special in regexes, too (as are ., so that .jpg will be an issue). You'd need \\\\ just to have a single literal backslash in the resulting regex.

Here's a possible fix:

function changeImage() {
    var image = document.getElementById("myImgId");
    if (/photo2\.jpg$/.test(image.src)) {
        image.src = "C:\\Users\\USER\\Desktop\\GRAPHICS\\photo3.jpg";
    } else {
        image.src = "C:\\Users\\USER\\Desktop\\GRAPHICS\\photo1.jpg";
    }
}

Those Windows paths will get converted to URLs on assignment.

Or perhaps you'd like to cycle through the three images:

function changeImage() {
    var image = document.getElementById("myImgId");
    image.src = image.src.replace(/photo(\d)\.jpg$/, function(m, c0) {
        var next = +c0 % 3 + 1;
        return "photo" + next + ".jpg";
    });
}

Each time you call it, that will advance to the next photo, wrapping-around from 3 to 1.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • ,I want to enter the event data in the form element from the furnction to capture the mount click points.I'am using >>>>>document.getElementById("sampleform").x=PosX; is it fine?It doesn't add the input into required field in the form

    x:

    – Akshay Sable Mar 07 '16 at 14:41