mccincol
mccincol

Reputation: 13

Change an image using radio buttons

I am trying to figure out how to use radio buttons to change an image to different images. I would like to use javascript and html/css to achieve this, but I'm not that polished with my javascript.

I know there are other answers to his here, but they seem to mostly involve backgrounds/divs and jQuery, but I don't really understand jQuery that well.

Here's my code:

HTML:

<form action="" id="animals">
<input type="radio" id="bunnybutton" name="animal" value="bunny" onClick="changeSrc()">bunny<br>
<input type="radio" id="kittybutton" name="animal" value="kitty" onClick="changeSrc()">kitty
    </form>
<img src="https://pbs.twimg.com/profile_images/447374371917922304/P4BzupWu.jpeg" id="picture" width=600px>

JAVASCRIPT:

function changeSrc() {
    if (document.getElementById("bunnybutton").checked) {
    document.getElementById("picture").src = "https://pbs.twimg.com/profile_images/447374371917922304/P4BzupWu.jpeg";
    } else if (document.getElementById("kittybutton").checked) { 
    document.getElementById("picture").src = "http://cutewallpaperss.com/wp-content/uploads/2015/01/cute_cats__cats_picture_cute_wallpaperss_hd_for_mobile.jpg";
    }
}

Upvotes: 1

Views: 2939

Answers (1)

Andre Lehnert
Andre Lehnert

Reputation: 531

Here in the code-editor your code works pretty well!

function changeSrc() {
    if (document.getElementById("bunnybutton").checked) {
    document.getElementById("picture").src = "https://pbs.twimg.com/profile_images/447374371917922304/P4BzupWu.jpeg";
    } else if (document.getElementById("kittybutton").checked) { 
    document.getElementById("picture").src = "http://cutewallpaperss.com/wp-content/uploads/2015/01/cute_cats__cats_picture_cute_wallpaperss_hd_for_mobile.jpg";
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<form action="" id="animals">
<input type="radio" id="bunnybutton" name="animal" value="bunny" onClick="changeSrc()">bunny<br>
<input type="radio" id="kittybutton" name="animal" value="kitty" onClick="changeSrc()">kitty
    </form>
<img src="https://pbs.twimg.com/profile_images/447374371917922304/P4BzupWu.jpeg" id="picture" width=600px>

Upvotes: 1

Related Questions