Sam Kortstee Sam Kortstee - 24 days ago 9
Javascript Question

''x'' is not a function

The function should return "This is True" however it doesn't appear to be working. It is telling me


randomQuestion
is not defined.


What am I doing wrong?

//Questions
function randomQuestion() {
var quest = "this is true";
var string_length = 1;
var randomstring = "";

for (var i=0; i<string_length; i++)
{
var rnum = Math.floor(Math.random() * quest.length);
randomQuestion += quest.substring(rnum,rnum+1);
}

document.questions.questfield.value = randomQuestion;
}

<!--Questions form-->
<form name="questions">
<input type="button" value="question" onClick="randomQuestion();">&nbsp;
<input type="text" name="questfield" value="">
</form>

Answer

The name of your function is randomQuestion, but in your function, you write:

randomQuestion += ...

I noticed that you didn't use the variable randomstring in your function. Maybe you want to use randomstring += instead of using randomQuestion += ...?

Here is the code I edited:

<html>
    <body>
        <script>
            function randomQuestion() {
                var quest = "this is true";
                var string_length = 1;
                var randomstring = "";
                var i = 0;
                var rnum = 0;
                for (i = 0; i < string_length; i++) {
                    rnum = Math.floor(Math.random() * quest.length);
                    randomstring += quest.substring(rnum, rnum + 1);
                }
                document.questions.questfield.value = randomstring;
            }
        </script>
        <form name="questions">
            <input type="button" value="question" onclick="randomQuestion();">
            <input type="text" name="questfield" value="">
        </form>
    </body>
</html>