创建一个表单。我只想进行表单验证。使用javascript来完成这项工作。在jS代码内部创建了一个名为check的函数。在该函数中,如果某些用户将输入字段留空,则该函数返回false,我认为可以限制用户,但不会发生。我的问题是同时解决getElement ..()方法和表单验证。
function check(){
//fname is the value provided into the input field
var fname = document.getElementsByClassName('fname').value;
//checks the inpur field and it is blank then return false
if (fname == '') {
return false;
}
else {
//if the input field is provided then will pass the validity
return true;
}
}
<div class="form">
<!-- created the class here and named form-->
<form class="" action="output.html.php" method="post" onsubmit="return check()">
<!-- called the check function-->
<input class="fname" type="text" name="name" value="" placeholder="Name">
<button type="submit" name="button">Send</button>
</form>
</div>
答案 0 :(得分:0)
问题在于getElementsByClassName
返回一个数组,因此您应该使用document.getElementsByClassName('fname')[0].value
或document.querySelector('.fname').value
(querySelector
仅返回第一个找到的实体)
答案 1 :(得分:0)
这是执行后我完整的代码。
function check(){
//fname is the value provided into the input field
var fname = document.getElementsByClassName('fname')[0].value;
//var fname = document.querySelector('.fname').value;
//checks the input field and if it is blank then return false
if (fname == '') {
return false;
}
else {
//if the input field is provided then will pass the validity
return true;
}
}
<div class="form">
<!-- created the class here and named form-->
<form class="" action="output.html.php" method="post" onsubmit="return check()">
<!-- called the check function-->
<input class="fname" type="text" name="name" value="" placeholder="Name">
<button type="submit" name="button">Send</button>
</form>
</div>