user2514364
user2514364

Reputation: 139

javascript radio button value get null

In the javascript, I have the pointer to get the name of the fruit. But the alert always shows null. I checked my logic but unable to find the problem. Any suggestions? thanks!

 <!DOCTYPE html>
    <html>
    <head>
        <title>My Fruit</title>
        <script type="text/javascript">
        function checkFruit(){
            var fruit_radio_pointers = document.querySelector('[name="fruit"]'); 
            var which_fruit = null;
            for(var i=0; i<fruit_radio_pointers.length; i++){
                if(fruit_radio_pointers[i].checked){
                    which_fruit = fruit_radio_pointers[i].value;  
                    break;            
                }    
            }
            alert(which_fruit);
        }

        //document.getElementById("my_btn").addEventListener("click", checkFruit, false);
        </script>
    </head>
    <body>
    <p>
        <input name="fruit" type="radio" value="apple" /> Apple<br />
        <input name="fruit" type="radio" value="cherry" /> Cherry
    </p>
    <p>
       <button id="my_btn" onclick="checkFruit()" >Which Fruit?</button>

    </p>
    </body>
    </html>

Upvotes: 0

Views: 1100

Answers (1)

Shawn31313
Shawn31313

Reputation: 6052

Use querySelectorAll:

var fruit_radio_pointers = document.querySelectorAll('[name="fruit"]'); 

querySelector only returns the first found match (not as an array).
It is equal to document.querySelectorAll('[name="fruit"]')[0].
As you may have figured out, querySelectorAll returns all of the found matches as an array.

Example

Upvotes: 4

Related Questions