简体   繁体   English

JavaScript检查以查看总和是否正确

[英]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. 我想要javascript检查,看看用户是否给出了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 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 我试一试,但我的JavaScript技能几乎不存在

I assume that you call validate() on the form's submit event (ie onsubmit="validate()" ). 我假设你在表单的submit事件上调用validate() (即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. 请注意,我们还使用parseInt()来防止JavaScript将值视为字符串,然后将它们与+ literal连接起来。 If we don't use parseInt() , JavaScript will interpret 6 and 4 as 64 , rather than 10 . 如果我们不使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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