Alessa Mattia
Alessa Mattia

Reputation: 11

Radio buttons to change an image (Javascript/HTML)

I have 3 images that must be changed when the corresponding radio button is clicked. The images are called spaghetti.jpg, salade.jpg and cremeglacee.jpg. They are in a folder called images.

So far, this is what I have and it isn't working. The first image (spaghetti.jpg) loads when I open the page but when I click on the radio buttons, the images don't change.

<p>
<img src="images/spaghetti.jpg" alt="spaghetti" name="Spaghetti" />

Spaghetti <input type="radio" name="demo" value="spaghetti" checked
           onclick="image.src='images/spaghetti.jpg'"/> <br>
Salade <input type="radio" name="demo" value="salade"
           onclick="image.src='images/salade.jpg'"/> <br>
Cr&egrave;me glac&eacute;e <input type="radio" name="demo" value="cremeglacee"
           onclick="image.src='images/cremeglacee.jpg'"/> <br> <br>
</p>

Upvotes: 0

Views: 48

Answers (1)

Matthew Bergwall
Matthew Bergwall

Reputation: 340

$(document).ready(function(){
        $("input:radio[name=demo]").click(function() {
            var value = $(this).val();
            var image_name;
            if(value == 'spaghetti'){
                image_name = "images/spaghetti.jpg";
            }else{
                if(value == 'salade'){
                    image_name = "images/salade.jpg";
                }else{
                    image_name = "images/cremeglacee.jpg";
                }
            }
             $('#imgS').attr('src', image_name);
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="images/spaghetti.jpg" alt="spaghetti" name="Spaghetti" id="imgS"/>

Spaghetti <input type="radio" name="demo" value="spaghetti"/> <br>
Salade <input type="radio" name="demo" value="salade"/> <br>
Cr&egrave;me glac&eacute;e <input type="radio" name="demo" value="cremeglacee"/> <br> <br>

Using JQUERY, you can do this very easily, check the above snippet. When the user clicks the input, it checks what value the radio button is, and then based off that it changes the src attribute of the image to the corresponding image.

Matt

Upvotes: 1

Related Questions