如何在提交表单之前检查2个输入字段的计算答案

时间:2016-09-02 09:14:55

标签: javascript php forms

我有一个注册表单,其中包含2个字段,包括随机int和答案的结果输入字段 提交时,检查字段不是空的Javascript代码 我还试图计算2个字段并将其与结果值进行比较

这是HTML:

<form method="post" id="contactForm" enctype="multipart/form-data" name="q_sign">
<input type="text" name="q_name" id="senderName"/>
<input type="text" name="q_mail" id="senderEmail" />
<input name="val1" type="text" disabled id="val1" value="php random value1" readonly="readonly" />
<input name="val2" type="text" disabled id="val2" value="php random value2" readonly="readonly" />
<input type="text" name="total" id="total" />

<input type="submit" id="sendMessage" name="sendMessage" value="Register" onClick="return check_data(this.form)" />

Javascript部分:

function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);

if(document.q_sign.q_name.value==''){
    alert("please enter your name");
    return false;
}else if(document.q_sign.q_mail.value==''){
    alert("please enter your email");
    return false;
}else if(document.q_sign.total.value!=(val1+val2)){ //Issue is here
    alert("wrong answer");
    return false;
}else{
    return true;
}}

1 个答案:

答案 0 :(得分:0)

maybe this is your expect below


function check_data(form) {
    var val1 = (document.q_sign.val1.value);
    var val2 = (document.q_sign.val2.value);
    if (document.q_sign.total.value != (eval(val1) + eval(val2))) {
        alert("wrong answer");
        return false;
    } else {
        return true;
    }
    }