Jump to content

radio button value


jwzumwalt

Recommended Posts

I am trying to get the value of a radio button.

The value of the radio button should get put into the answer box.
Why won't the radio value get returned and/or shown?
Thx
 

<head>
  <script>
    function test() {
      var myinput = document.getElementById("guess").value;
      document.getElementById("answer").value = myinput;
    }
  </script>  
</head>

<body>
  <input type="radio" name="guess" value="1"> One<br>
  <input type="radio" name="guess" value="2"> Two<br>
  <input type="radio" name="guess" value="3"> Three<br>
  <input type="radio" name="guess" value="4"> Four<br>      
  <br>
  <br>
  Answer  <input type="text" id="answer" size=8 style="background-color:#cfc;">
  <br>
  <br>
  <button onclick="test()">Calculate</button></body>

 

Link to comment
Share on other sites

The clue is in the method name 'document.getElementById()'. None of those radio button has a id ref, and it would be impractical to use that anyway,

The options are to use getElementsByName("guess") and loop through them all, identify which is checked and retrieve that elements value.

            function test() {
                var myinput = document.getElementsByName("guess");

                for (i = 0; i < myinput.length; i++) {
                    if (myinput[i].checked)
                    {
                        document.getElementById("answer").value = myinput[i].value;
                    }
                }
            }

OR use the newer 'document.querySelectorAll()'

            function test() {
                var myinput = document.querySelectorAll('input[name="guess"]:checked')[0];
                document.getElementById("answer").value = myinput.value;
            }

 

Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

dsonesuk - Thank you for taking the time to explain the problem AND provide the solution.
I use to write most my web programs in PHP and have started to convert many of them to JS - would have never figured this out :)
I do keep good notes, and won't have to go through this again!

Edited by jwzumwalt
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...