skip to Main Content

I am trying to make a geography quiz and I have the logic made however I am having trouble with retrieving a value from a form. The value is retrieved in a function that is started by the button and the button works I tested this by commenting out the line of code retrieving the input.(I am new to Stack overflow so I may have pasted a bit too much code as I don’t really know how much is needed)

<script>
    let Question_No = 1;
    let Hanswer = "";

</script>

<body>

    <p id="Question">1. Question 1</p>

    <form name="form"></form>
    <input type="text" name="inputbox" id="inputbox"  value=""><br>
    <input type="submit" value="Submit" onclick="functionmain(this.form)">
    </form>
</body>

<script>

    function functionmain(form) {
        Hanswer = getElementById("inputbox").value; //This is the area with the problem

        if (Question_No == 1) {
            document.getElementById("Question").innerHTML = ("2.Question 2");
            if (Hanswer == "1") {
                alert("Correct");
            }
            else {
                alert("Wrong");
            }

This is the error that I got when I tried to press the button and the affected area was not commented away( I omitted file names):

Uncaught ReferenceError ReferenceError: getElementById is not defined
at functionmain (:33:13)
at onclick (:26:79)

I have tried doing what was suggested here: javascript not getting value of input box but it didn’t seem to work.

Sorry if the solution is obvious I am a novice programmer and have only started JavaScript this school year. Thank you in advance

2

Answers


  1. This is a simple fix. Just a typo at Hanswer or rather an accidental exclusion. You just need to add document in from of getElementById. The new line would look like this:

    Hanswer = document.getElementById("inputbox").value; //This is the area with the problem
    
    Login or Signup to reply.
  2. Before calling any method from the DOM (Document Object Module), you must call the module first and then accessing the method.
    That’s why you need to do:

    Hanswer = document.getElementById("inputbox").value;
    

    But when using methods or properties inside the BOM (Browser Object Module), you can call it directly, eg.

    localStorge.setItem();
    window.localStorge.setItem();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search