A.Bachesque A.Bachesque - 27 days ago 15
Javascript Question

Output selected button value or name

I'm trying to get values from the button and output in the window what has been selected, for me says array is undefined.

Please help correct my mistake.

<input type="radio" name="flavor" id="vanilla" value="Vanilla" checked="checked" />Vanilla
<input type="radio" name="flavor" id="choc" value="Chocolate" />Chocolate
<input type="radio" name="flavor" id="strawberry" value="Strawberry" />Strawberry

var flavorArray = ["","","Vanilla","Chocolate","Strawberry"];

var flavorValue = document.querySelector('input[name = "flavor"]:checked').value;

flavorArray[flavorvalue] -<< my output

Answer

Try this code:

<html>
    <head>
        <title>Checkbox</title>
    </head>
    <body>

        <input type="radio" name="flavor" id="vanilla" value="Vanilla" checked="checked"/>Vanilla 
        <input type="radio" name="flavor" id="choc" value="Chocolate" />Chocolate
        <input type="radio" name="flavor" id="strawberry" value="Strawberry"/>Strawberry


    <script>

         var flavorArray = ["","","Vanilla","Chocolate","Strawberry"];
         var flavorValue = document.querySelector('input[name="flavor"]:checked').value;

         console.log(flavorArray[flavorArray.indexOf(flavorValue)])
    </script>
    </body>
</html>
Comments