我正在尝试使用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;
}
}
你认为男孩是什么?
答案 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;
}
}