简体   繁体   中英

JavaScript doesn't handle a form input

I have a simple text input in my form which I want to validate against a specific word. It's quite simple however the form is not handled by my code and on submit it doesn't do anything:

This is the HTML for the form.

<div id="wrapper">
    <section><p id="showtime"></p></section>
    <section><p id = "quest"></p></section>
    <p id = "fieldA"></p>
    <form method="post" action="" name="AnsForm" onsubmit="return checkForm()">
        <label class="choice" for="answer">Your Answer</label><br/> 
        <input type="text" name="answer"></input>
    </form><br/>
    <input type="submit" value="Submit">
    <div id="footer">
        <p>User1234</p>
        <p>Level: </p><p id="level"></p>
    </div>
</div>

And JavaScript the function that doesn't work is checkForm()

<script language="JavaScript">
var difficulty = "easy";
var question = "Name of the only mammal that lays eggs";


document.getElementById("quest").innerHTML = question;
function startTime() {
    var today=new Date();
    var h=today.getHours();
    var m=today.getMinutes();
    var s=today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('showtime').innerHTML = h+":"+m+":"+s;
    var t = setTimeout(function()
    {startTime()},500);
}

function checkTime(i) {
    if (i<10) {
    i = "0" + i;
    }  // add zero in front of numbers < 10
    return i;
}

function checkForm() {
    var answer = "platypus";
    var ansrs = document.forms["AnsForm"]["answer"].value;
    var ansrL = ansr.toLowerCase();
    if (ansrL == answer) {
        document.getElementById("fieldA").innerHTML = "Your answer is correct!";    

    }
    else {
        document.getElementById("fieldA").innerHTML = "Sorry, try again!";
        return false;
    }
}


</script>

There are few corrections:

var ansrs = document.forms["AnsForm"]["answer"].value;
var ansrL = ansr.toLowerCase();
            ^^^^ wrong spelling, it is - ansrs 

Also the submit button needs to be enclosed within form tag:

</form><br/>
    <input type="submit" value="Submit"> <!-- move it inside form tag -->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM