Connecting Tech Pros Worldwide Forums | Help | Site Map

change an image based on selected option

Xerxes
Guest
 
Posts: n/a
#1: Jan 31 '06
Hi,
I have 3 images of the same product in 3 different colors. I want to
display the correct color product based on what color is selected using
a dropdown.
Can you please tell me how I can do the swapping of the images?

TIA.


Nathan White
Guest
 
Posts: n/a
#2: Jan 31 '06

re: change an image based on selected option


Below is all you need. Realize that you should probably pull the
onchange javascript out and wrap it in a function and do DOM checking
first so you don't product errors in old browsers.

<select onchange="document.getElementById('productPic').sr c =
this.options[this.selectedIndex].value;>
<option value="null">-- Please Select Product --</option>
<option value="img/src">Image 1</option>
<option value="img/src">Image 2</option>
<option value="img/src">Image 3</option>
</select>

<img id="productPic" src="blank.gif">

Thomas 'PointedEars' Lahn
Guest
 
Posts: n/a
#3: Feb 1 '06

re: change an image based on selected option


Nathan White wrote:
[color=blue]
> [...] Realize that you should probably pull the onchange javascript out
> and wrap it in a function and do DOM checking first so you don't product
> errors in old browsers.[/color]

True, however:
[color=blue]
> <select onchange="document.getElementById('productPic').sr c =
> this.options[this.selectedIndex].value;>[/color]

Oh my. The `document.images' collection exists:

<select onchange="document.images['productPic'].src =
this.options[this.selectedIndex].value;>

See also <URL:http://pointedears.de/scripts/test/hoverMe/> for a much
less error-prone approach.
[color=blue]
> <option value="null">-- Please Select Product --</option>[/color]

This should not be `null', but refer to a default image. In fact, this
option is nonsensical: The default option should be the one specifying
the initial `src' attribute value of the `img' element.
[color=blue]
> [...]
> </select>
>
> <img id="productPic" src="blank.gif">[/color]

Although the `id' attribute should work with `document.images', the `name'
attribute is fully downwards compatible with it to DOM Level 0 (NN3+/IE3+).


PointedEars
Xerxes
Guest
 
Posts: n/a
#4: Feb 1 '06

re: change an image based on selected option


Thanks a lot. It did the job.

Closed Thread