我试图在另一个函数中调用一个函数,但它不起作用。
P.S 我是 JS 初学者
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate() {
madatorychk(name);
//This functions makes sure that madatory fields are filled
function madatorychk(fieldid) {
var node = document.myForm.fieldid;
if (node.value == "") {
alert("This field cannot be left empty");
document.myForm.fieldid.focus();
return false;
}
}
}
//-->
</script>
<form method="get" onsubmit="return(validate());" name="myForm">
<label>Name: <input type="text" id="name"></label> </form>
</form>
最佳答案
您需要使用 bracket notation使用变量名访问对象属性。
因此 document.myForm.fieldid
(它试图采用字面上名为 fieldid
的表单元素)是不正确的,应该是 document.myForm[字段id]
:
function validate() {
return madatorychk('name');
//This functions makes sure that madatory fields are filled
function madatorychk(fieldid) {
var node = document.myForm[fieldid];
if (node.value == "") {
alert("This field cannot be left empty");
document.myForm[fieldid].focus();
return false;
}
}
}
为此还要确保您已命名表单元素:
Name: <input type="text" name="name" />
最后,非常重要的是你需要返回madatorychk
的结果:
return madatorychk('name');
还有一件事。您可能不希望不仅允许空的用户名,而且也不想允许只有空格的用户名,因此在验证之前 trim 输入:
if (node.value.trim() == "") {
alert("This field cannot be left empty");
document.myForm[fieldid].focus();
return false;
}
关于javascript - 在另一个函数中调用 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30421093/