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

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

问题描述:

I have a register form with 2 fields includes random int and a result input field for the answer there's a Javascript code to check fields are not empty when submitting I'm trying also to calculate the 2 fields and compare it with the result value

Here's the 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 part :

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;
}}

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;
    }
    }