JavaScript检查总和是否正确


JavaScript checking to see if a sum is correct

我希望javascript检查用户是否对php生成的两个随机数给出了正确的答案。用户在提供的文本框中手动输入数字。

<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="answerswer" 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尝试了一下,但我的JavaScript技能几乎不存在

我假设您在表单的submit事件(即onsubmit="validate()")上调用validate()。如果没有,则需要以某种方式调用该函数。

其次,你的逻辑是错误的。您要检查答案是否正确(==就是这样做的),然后在正确时告诉用户答案不正确,在不正确时允许。

改变你的逻辑如下:

function validate()
{
    if((parseInt(Contact.number1.value) + parseInt(Contact.number2.value)) == Contact.answer.value)
    {
        return true;
    }   
    alert("Wrong answer number")
    return false
}

请注意,我们还使用parseInt()来防止JavaScript将值视为字符串,然后将它们与+文本连接。如果我们不使用parseInt(),JavaScript将把64解释为64,而不是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>