Update src image with JavaScript?

I have one image ( img.png

) changing its content after changing a combo box.

The problem is that the content of the image does not change when the combo box on the page changes.

I tried using JavaScript like this:

function SwitchPic(pic) {
    pic.src = "img.png";
}

      

and the tag img

:

<img src='img.png' id='img1' name='img1'>

      

and the combo tag:

<select name="users" onchange="show(this.value);SwitchPic(img1);">
    <option value="">Select a Number:</option>
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

      

It worked the first time I change this setting, but when I change the setting it saves the image without changing it.

How can I solve this?

+3


source to share


4 answers


Could be a cache problem Instead of just using the filename, add a random part to it like "img.png? Random", this way you force the browser to look for the image on the server again, but the random part will be discarded anyway and the file will still be found The easiest way to do this is to add the date / time after the expansion



+4


source


You are trying to pass your image tag as smg1

, but you are not declaring that it is your image element.

try this:

SwitchPic('img1');

      



and then in your handler:

function SwitchPic(picID) {
  var pic = document.getElementById(picID);
  pic.src = "img.png";
}

      

In this scenario, you pass in the id of the element you want to change, then get the actual element inside your handler.

+3


source


Two problems:

  • Your function only changes it to this image, not toggle it.
  • You are passing in a variable img1

    that is undefined. You need to pass in the id of the image and then use it to get the node.

So, you need to use document.getElementById()

to get the image and then you need to switch every time:

var clicked = false;

function SwitchPic(pic) {
    var image = document.getElementById(pic);
    if(!clicked){
        image.src = "otherImg.png";
        clicked = true;
    }else{
        image.src = "img.png";
        clicked = false;
    }
}

      

Demo

0


source


I think your problem is:

  • An image named img.png.
  • The function keeps changing the actual img.png to a different image but with the same name img.png
  • You are reassigning the src attribute of the image tag, but the image is not updated.

If so, then it is a browser image caching issue. refer to the links below:

How to reload / update an element (image) in jQuery

how to force chrome not to reload images with the same url until the page is refreshed like firefox

How to make web browser not cache images

hope this helps!

0


source







All Articles