给了一个难题,要弄清哪种方法仅使用js进行表单验证,这里的奇特之处是没有表单名称,类型不使用ID,但它们确实具有名称,但主要目的是是为了确保至少在每种输入类型上都输入了一些数据(例如,全名甚至可以是1个字母,只要是一个字符即可)。要注意的另一件事是我无论如何都无法更改html代码。由于我无法在验证中使用表单名称,因此我在网上看到的示例很有帮助,但不足以继续进行。任何帮助将不胜感激。
<form action = "form.html" method = "get"><br/>
Name:<input type = "text" name = "fullname" value="Enter Full Name"/><br/>
Gender:<br/>
Male<input type = "radio" name = "gender" value="male"/>Female<input type = "radio" name = "gender"
value="female"/><br/>
Hobbies<br/>
Baseball <input type = "checkbox" name = "hobbies[]" value = "baseball" />
Football <input type = "checkbox" name = "hobbies[]" value = "football" />
Hockey <input type = "checkbox" name = "hobbies[]" value = "hockey" /><br/>
Favorite Show <select name = "show">
<option value = "">Choose Below</option>
<option value = "ATHF">Aqua Teen Hunger Force</option>
<option value = "Family Guy">Family Guy</option>
<option value = "Simpsons">Simpsons</option>
</select><br/>
Comments<br/>
<textarea cols = "50" rows = "6" name = "comments">Enter Comments</textarea><br/>
<input type = "submit" name = "submit" value = "enter me" />
</form>
它杂乱无章,但可以正常工作。我不更改HTML部分的任何内容。
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
</style>
</head>
<body>
<form action = "form.html" method = "get"><br/>
Name:<input type = "text" name = "fullname" value="Enter Full Name"/><br/>
Gender:<br/>
Male<input type = "radio" name = "gender" value="male"/>Female<input type = "radio" name = "gender"
value="female"/><br/>
Hobbies<br/>
Baseball <input type = "checkbox" name = "hobbies[]" value = "baseball" />
Football <input type = "checkbox" name = "hobbies[]" value = "football" />
Hockey <input type = "checkbox" name = "hobbies[]" value = "hockey" /><br/>
Favorite Show <select name = "show">
<option value = "">Choose Below</option>
<option value = "ATHF">Aqua Teen Hunger Force</option>
<option value = "Family Guy">Family Guy</option>
<option value = "Simpsons">Simpsons</option>
</select><br/>
Comments<br/>
<textarea cols = "50" rows = "6" name = "comments">Enter Comments</textarea><br/>
<input type = "submit" name = "submit" value = "enter me" />
</form>
</body>
<script type="text/javascript">
function validate(){
name = document.getElementsByName("fullname")[0].value.length
gender1 = document.getElementsByName("gender")[0].checked
gender2 = document.getElementsByName("gender")[1].checked
hobbies1 = document.getElementsByName("hobbies[]")[0].checked
hobbies2 = document.getElementsByName("hobbies[]")[1].checked
hobbies3 = document.getElementsByName("hobbies[]")[2].checked
show = document.getElementsByName("show")[0].value
comment = document.getElementsByName("comments")[0].value.length
if(name==0 || (!gender1 && !gender2) || (!hobbies1 && !hobbies2 && !hobbies3) || comment==0){
alert("please fill all")
}
}
button = document.getElementsByName("submit")
eButton = button[0].addEventListener("click",validate)
</script>
</html>