我在页面中有一些字段(动态创建),我正在尝试提交表单上的每个元素.Bellow代码是示例,只有 txtAge 字段验证, txtName 没有验证。是否有任何选项可以用波纹管代码验证每个字段?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
function txtName_FormValidation() {
document.getElementById('entryForm').onsubmit = function (e) {
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
return false;
};
}
}
function txtAge_FormValidation() {
document.getElementById('entryForm').onsubmit = function (e) {
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
return false;
};
}
}
</script>
</head>
<body onload="txtName_FormValidation(); txtAge_FormValidation()">
<form id="entryForm">
<input type="text" id="txtName" />
<span id="span_txtName"></span>
<br />
<input type="text" id="txtAge" />
<span id="span_txtAge"></span>
<br />
<button type="submit" value="Sebmit">Submit</button>
</form>
</body>
</html>
答案 0 :(得分:1)
你为什么不这样做?
从同一个函数调用所有验证?
<script>
document.getElementById('entryForm').onsubmit = function(e){
txtName_FormValidation(e);
txtAge_FormValidation(e);
}
function txtName_FormValidation(e) {
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
return false;
};
}
function txtAge_FormValidation(e) {
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
return false;
};
}
</script>
答案 1 :(得分:0)
您正在替换第一个onsubmit事件,因此只调度第二个函数。
你可以试试这个:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('entryForm').onsubmit = function (e) {
e.preventDefault();
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
};
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
};
}
}, false);
</script>
</head>
<body >
<form id="entryForm">
<input type="text" id="txtName" />
<span id="span_txtName"></span>
<br />
<input type="text" id="txtAge" />
<span id="span_txtAge"></span>
<br />
<button type="submit" value="Sebmit">Submit</button>
</form>
</body>
</html>