使用javascript函数验证表单

时间:2017-03-24 05:48:01

标签: javascript html forms

我正在尝试使用JavaScript函数验证表单。我认为它有效,但输出几乎立即消失。

以下是相关代码:

<form name="myForm">
    Your Age: <input type="text" name="age">
    <input type="submit" value=" Send " id="submit">
</form>



document.getElementById("submit").addEventListener("click", validate);

function validate () {

    var x = document.forms["myForm"]["age"].value;

    if (x > 0) {
        document.getElementById("demo").innerHTML = "Congrats you have entered x, your answer has been submitted";
    }
    else {
        document.getElementById("demo").innerHTML = "ERROR: Please enter a valid age";
        return false;
    }

}

你认为男孩是什么?

1 个答案:

答案 0 :(得分:1)

您必须通过$lang = "kan"函数中的event参数来阻止默认行为,并使用validate来防止默认行为。

如果条件满足,请使用.preventDefault();函数通过JavaScript提交表单 为此,请添加submit()action或使用ajax。

method
document.getElementById("submit").addEventListener("click", validate);

function validate (e) {
    e.preventDefault();
    var x = document.forms["myForm"]["age"].value;

    if (x > 0) {
        document.getElementById("demo").innerHTML = "Congrats you have entered x, your answer has been submitted";
        //submit your form here by using formelement.submit();
    }
    else {
        document.getElementById("demo").innerHTML = "ERROR: Please enter a valid age";
        return false;
    }

}