Home > Software engineering >  How to get different images to display when clicking on a radio button using JavaScript?
How to get different images to display when clicking on a radio button using JavaScript?

Time:12-28

I have been trying for days to figure this out. I need to click on a radio button and have the image change. For example if I click on the golden gate bridge radio button I need it to switch the image to the picture of the bridge. So far I can only get it to click on the image and then the image changes but that is not what I want to do. I have tried many different ways and nothing works. I am new to JavaScript.

<!DOCTYPE html>
<html>
<body>
<!--Statue of Liberty image-->
<img id="statue" onclick="changeImage()" 
src=
'https://www.history.com/.image/ar_4:3,c_fill,cs_srgb,fl_progressive,q_auto:good,w_1
200/MTY1MTc1MTk3ODI0MDAxNjA5/topic-statue-of-liberty-gettyimages-960610006-promo.jpg' 
width="300">


<p>Click the picture to change image.</p>

<script>
//Functon that changes mage when clicking on the image
function changeImage() {
  var image = document.getElementById('statue');

  if (image.src.match("statue")) {
  image.src=

 'https://www.history.com/.image/ar_4:3,c_fill,cs_srgb,fl_progressive,q_auto:good,w_1200/MTY1MTc3MjE0MzExMDgxNTQ1/topic-golden-gate-bridge-gettyimages-177770941.jpg';
  } 
  else if (image.src.match("bridge"))
  {
    image.src = "https://media-cldnry.s-nbcnews.com/image/upload/newscms/2020_26/3392557/200625-mount-rushmore-al-0708.jpg";
}
}
</script>
<!-- Radio buttons-->
    <form>
    <input type="radio" id = "statue-button" name = "landmark" checked value="statue"onClick= ('toggleImage')>Statue of Liberty<br>
    <input type="radio" id = "bridge-button" name="landmark" value="bridge">Golden Gate Bridge<br>
    <input type="radio" id = "rushmore-button" name="landmark" value="rushmore">Mount Rushmore<br>
    </form>

</body>
</html>

CodePudding user response:

There are a few things you should correct so that your code works as expected.

<input type="radio" id = "statue-button" name = "landmark" checked value="statue"onClick= ('toggleImage')>Statue of Liberty<br>

should be changed to

<input type="radio" id="statue-button" name="landmark" checked value="statue" onClick="changeImage('statue')">Statue of Liberty<br>

So that the spaces are in the correct places and the onClick attribute is inside quotes.

Then inside the function changeImage() you should check the parameter (in my example named value) simply by comparison. The method match is intended to be used with regular expressions and not needed here.

function changeImage (value) {
    var image = document.getElementById('statue');
    if (value === 'statue') {
        image.src = '...';
    } else if (value === 'bridge') {
        image.src = '...';
    }
}

CodePudding user response:

Well I found a solution to your problem.

I basically added click event Listeners for each of the radio inputs, then when an input was clicked I got hold of its value attribute using the event passed through the callback function and compared it to each of the elements from the array radioInputs.

If it matched then I changed the img src attribute using the index of the input (which I got from the forEach loop) on the array urls.

Besides I changed the clicked input's checked attribute to true and removed this attribute from the other 2 inputs.

Update: I didn't really have to change the checked attributes because the inputs all had the same name and they automatically did that. Sorry for my mistake. Updated the code snippets accordingly.

Here's the code (a html file and a script):

let urls = [
    'https://www.history.com/.image/ar_4:3,c_fill,cs_srgb,fl_progressive,q_auto:good,w_1200/MTY1MTc1MTk3ODI0MDAxNjA5/topic-statue-of-liberty-gettyimages-960610006-promo.jpg',
    'https://www.history.com/.image/ar_4:3,c_fill,cs_srgb,fl_progressive,q_auto:good,w_1200/MTY1MTc3MjE0MzExMDgxNTQ1/topic-golden-gate-bridge-gettyimages-177770941.jpg',
    "https://media-cldnry.s-nbcnews.com/image/upload/newscms/2020_26/3392557/200625-mount-rushmore-al-0708.jpg"
]

let radioInputs = document.querySelectorAll("input");

radioInputs.forEach(function (input, index) {
    input.addEventListener('click', handleChange);
});

function handleChange(e) {
    let inputValue = e.target.value;

    radioInputs.forEach(function (input, index) {
        if (input.value === inputValue) {
            let image = document.getElementById("statue");
            image.src = urls[index];
        }
    });
}
<!DOCTYPE html>
<html>
<body>
<!--Statue of Liberty image-->
<img id="statue"
     src=
             'https://www.history.com/.image/ar_4:3,c_fill,cs_srgb,fl_progressive,q_auto:good,w_1
200/MTY1MTc1MTk3ODI0MDAxNjA5/topic-statue-of-liberty-gettyimages-960610006-promo.jpg'
     width="300">


<p>Click the picture to change image.</p>

<!-- Radio buttons-->
<form>
    <input type="radio" id="statue-button" name="landmark" checked value="statue">Statue of Liberty<br>
    <input type="radio" id="bridge-button" name="landmark" value="bridge">Golden Gate Bridge<br>
    <input type="radio" id="rushmore-button" name="landmark" value="rushmore">Mount Rushmore<br>
</form>

<script src="script.js"></script>
</body>
</html>

I hope you understood what I did here! Good luck on your next coding sessions!

  • Related