function test1form() {
var x =document.forms.myForm['fname1','fname2','fname3'].value;
if (x == ''){
alert('未填写');
return false;
}
}
<form name="myForm" action="" method="">
测试:<br>
<span style="color:red">*</span> <input type="text" name="fname1"><br>
<span style="color:red">*</span> <input type="text" name="fname2"><br>
<span style="color:red">*</span> <input type="text" name="fname3"><br>
<input type="submit" value="submit" onclick="test1form()"><br>
</form>
我想让这三个都必填,否则弹窗提示,测试只填fname1 fname2不会出现弹窗,为什么呢
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("必须填写姓名!");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/demo/action_page.php" onsubmit="return validateForm()" method="post">
姓名:<input type="text" name="fname">
<input type="submit" value="提交">
</form>
</body>
</html>
操作多个input,name做成相同的document.getElementsByName。class做成相同的document.getElementsByClassName
这有好多写法,你可以分别给这几个input绑定监听,或者给表单绑定一个监听,在提交的时候触发,检测有没有输入