The purpose is to switch the display of elements (images, etc.) depending on whether the radio button is checked or not.
Mostly you use onclick to activate JavaScript after the button is pressed.
However, writing code for each button is not efficient when there are many buttons.
So I want to make it a mechanism to know which radio button is checked with javascript and return the result.

This time I wrote a program that displays the corresponding image when the button is checked.
If i check the button whose name is kuma, the image of kuma.png will be displayed.
Is it possible to make this the above mechanism?

<! DOCTYPE html>
        <meta charset = "UTF-8">
        <style type = "text/css">
        img {
            width: 100px;
            height: 100px;
            margin: 10px;
        <script type = "text/javascript">
            function usa () {
            document.animal_img.src = "usa.png";
            function kuma () {
            document.animal_img.src = "kuma.png";
            <input type = "radio" name = "animal" value = "1" onclick = "usa ()">Rabbit
            <input type = "radio" name = "animal" value = "2" onclick = "kuma ()">bear</p>
            <img src = "usa.png" name = "animal_img">
  • Answer # 1

    Since modern CSS is rich, it may not be necessary to write JS
    (It is necessary to devise CSS instead, but it is easy because you can use it easily.)

    Demo: https://thimbleprojects.org/liveasnotes/532250/

    You can view and edit the code from the "Remix" button on the top right

      <input type = "radio" name = "myradio" id = "img1" checked>
      <label for = "img1">Gray</label>
      <input type = "radio" name = "myradio" id = "img2">
      <label for = "img2">Blue</label>
      <input type = "radio" name = "myradio" id = "img3">
      <label for = "img3">Green</label>

    The excerpt is the liver

    img {
      position: absolute;
      bottom: 0;
      left: 0;
      z-index: 1;
    input [name = "myradio"]: checked + label + img {
      z-index: 10;