Heather
Heather

Reputation: 25

Javascript - onchange image change

This should be fairly simple but it's not working and I'm not seeing it. I'm trying to get my image to change with the onchange method calling the displayImage function. Any ideas what I'm missing?

<html>
<head>
  <title>Select Image</title>
  <script type="text/javascript">
  function displayImage() {
    var image = document.getElementById("canvas");
    var newImage = image.option[image.selectedIndex].value;
  }
  </script>
</head>
<body>
  <form name="controls">
    <img id="canvas" src="pictures/fire1.jpg" />
    <select name="imageList" onchange="displayImage();">
      <option value="pictures/fire1.jpg">Fire 1</option>
      <option value="pictures/fire2.jpg">Fire 2</option>
      <option value="pictures/fire3.jpg">Fire 3</option>
      <option value="pictures/fire4.jpg">Fire 4</option>
</select>
  </form>
</body>
</html>

Upvotes: 0

Views: 11838

Answers (3)

Suchit kumar
Suchit kumar

Reputation: 11859

you can try this: change your select name to id.

<html>
<head>
  <title>Select Image</title>
  <script type="text/javascript">
  function displayImage() {
    var image = document.getElementById("imageList").value;
    document.getElementsByTagName("img")[0].setAttribute("src",image)
  }
  </script>
</head>
<body>
  <form name="controls">
    <img id="canvas" src="pictures/fire1.jpg" />
    <select id="imageList" onchange="displayImage();">
      <option value="pictures/fire1.jpg">Fire 1</option>
      <option value="pictures/fire2.jpg">Fire 2</option>
      <option value="pictures/fire3.jpg">Fire 3</option>
      <option value="pictures/fire4.jpg">Fire 4</option>
</select>
  </form>
</body>
</html>

Upvotes: 0

friedi
friedi

Reputation: 4360

Try this:

function displayImage() {
    var image = document.getElementById("canvas"),
        select = document.getElementsByTagName('select')[0];
    image.src = select.value;
}

or more compact:

function displayImage() {
    document.getElementById("canvas").src = document.getElementsByTagName('select')[0].value;
}

Here is the example

Upvotes: 1

rocky
rocky

Reputation: 7696

If you want to change the image of the canvas element based on value of the dropdown list, use something like:

<html>
<head>
  <title>Select Image</title>
  <script type="text/javascript">
  function displayImage(elem) {
    var image = document.getElementById("canvas");
    image.src = elem.value;        
  }
  </script>
</head>
<body>
  <form name="controls">
    <img id="canvas" src="pictures/fire1.jpg" />
    <select name="imageList" onchange="displayImage(this);">
      <option value="pictures/fire1.jpg">Fire 1</option>
      <option value="pictures/fire2.jpg">Fire 2</option>
      <option value="pictures/fire3.jpg">Fire 3</option>
      <option value="pictures/fire4.jpg">Fire 4</option>
</select>
  </form>
</body>
</html>

Add this to the function call and modify the function itself.

Upvotes: 1

Related Questions