[Solved] JavaScript function not running? [closed]


The main problem is that your global var userChoice has the same name as the function’s argument. The function getUserChoice over writes it’s parameters value with the values set in the conditionals. Then it does nothing with it; once you leave the function’s scope, it’s lost.

If you want the function to operate on the global variable, don’t give the function a parameter with the same name.

The second problem is that you assign the global varible userChoice the return value of your function, and since it doesn’t return anything, it actually over writes the value with undefined. So even if you did the above, it still wouldn’t work.

Fourth document.userInput isn’t defined. You need to query for it, e.g. document.getElementById('userInput').

All in all, a better solution would be to do this:

<html>
    <head>
        <script>
            var userChoice;

            var setUserChoice = function(event) {
                event.preventDefault();
                var choices = event.target.userChoice;

                for (var i =0; i < choices.length; i++) {
                    if (choices[i].checked) {
                        userChoice = choices[i].value;
                    }
                }

                event.target.choice.value = userChoice;
            }

            window.onload = function() {
                var form = document.getElementById('userInput');
                form.addEventListener('submit', setUserChoice, false);
            };
        </script>
    </head>

    <body>
        <form id="userInput">
                <input type="radio" name="userChoice" id="userChoice_rock" value="rock">Rock</input> </br>
                <input type="radio" name="userChoice" id="userChoice_paper" value="paper">Paper</input> </br>
                <input type="radio" name="userChoice" id="userChoice_scissors"value="scissors">Scissors</input> </br>
                <input type="radio" name="userChoice" id="userChoice_lizard" value="lizard">Lizard</input> </br>
                <input type="radio" name="userChoice" id="userChoice_spock" value="spock">Spock</input> </br>
                <input type="submit" value="Enter" /></br>
                <output name="choice"></output>
        </form>
    </body>
</html>

solved JavaScript function not running? [closed]