简体   繁体   中英

JavaScript checking to see if a sum is correct

Im wanting javascript to check to see if the user has given the correct answer to two random numbers generated by php. The user manually enters the number in the text box provided.

<input id="number1" name="number1" readonly="readonly" class="Add" value="<?php echo rand(1,4) ?>" /> + 
<input id="number2" name="number2" readonly="readonly" class="Add" value="<?php echo rand(5,9) ?>" /> =
<input type="text" name="answer" id="number" class="number" maxlength="2" />
<span id="comment"><div class="Lable">Please give the correct answer to the sum</div></span>

JavaScript

<script language="JavaScript">

function validate()
{

if (Contact.answer.value == Contact.number1.value + Contact.number2.value)
{
    alert("Wrong answer number")
    return false
}

return true;

}



</script>

Iv give it a shot but my JavaScript skills are almost none existent

I assume that you call validate() on the form's submit event (ie onsubmit="validate()" ). If not, you'll need to call the function somehow.

Secondly, your logic is the wrong way around. You're checking if the answer is correct (that's what == does), and then telling the user it's incorrect when it's correct, and allowing it when it's not.

Change your logic around as follows:

function validate()
{
    if((parseInt(Contact.number1.value) + parseInt(Contact.number2.value)) == Contact.answer.value)
    {
        return true;
    }   

    alert("Wrong answer number")
    return false
}

Notice that we also use parseInt() to prevent JavaScript treating the values as strings, and then concatenating them with the + literal. If we don't use parseInt() , JavaScript will interpret 6 and 4 as 64 , rather than 10 .

<script language="JavaScript">

function validate()
{
var answer = parseInt(document.getElementById("number1").value,     10)+parseInt(document.getElementById("number2").value, 10);
var v = parseInt(document.getElementById("captcha").value, 10);
if (answer != v)
{
    alert("Wrong answer number")
    return false
}

return true;
}



</script>

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