我是初学者,我的作业需要一些帮助。我无法弄清楚我做错了什么。标签和提交按钮显示在html中,但是当我点击提交按钮时,它不会验证表单。
我的任务是制作一个表格来输入你的名字。提交一个函数来验证名称,该函数将验证该名称不能为空,且必须超过6个字符。
<html>
<head>
<body>
<form name="myForm" autocomplete="on" onsubmit="return validateForm()">
<p><label>First name (required) <input type="text" id="firstName"
autofocus="autofocus" /> </label></p>
</form>
<input type="submit" name="S1" value="Submit response" />
<script>
function validateForm(){
var firstName=document.getElementById("firstName");
if (firstName.value.length<6){
alert("Please enter your first name (6 characters or more)");
firstName.focus();
return false;
}
alert("Thank you for your submission");
return true;
}
</script>
</body>
</head>
</html>
答案 0 :(得分:1)
在表单标记
中放置提交按钮
function validateForm() {
var firstName = document.getElementById("firstName");
if (firstName.value.length < 6) {
alert("Please enter your first name (6 characters or more)");
firstName.focus();
return false;
}
alert("Thank you for your submission");
return true;
}
&#13;
<html>
<head>
<body>
<form name="myForm" autocomplete="on" onsubmit="return validateForm()">
<p><label>First name (required)<input type="text" id="firstName"
autofocus="autofocus" /> </label></p>
<input type="submit" name="S1" value="Submit response" />
</form>
</body>
</head>
</html>
&#13;
答案 1 :(得分:1)
您的代码存在的问题是您尝试将结果返回给事件。活动不接受任何回复。所以试试这个;
<html>
<body>
<form name="myForm" autocomplete="on" onsubmit="validateForm()">
<p>
<label>First name (required)</label>
<input type="text" id="firstName" autofocus="autofocus" />
</p>
<input type="submit" name="S1" value="Submit response" />
</form>
<script>
function validateForm(){
var firstName=document.getElementById("firstName");
if (firstName.value.length<6){
alert("Please enter your first name (6 characters or more)");
firstName.focus();
return false;
}
alert("Thank you for your submission");
document.getElementsByTagName("form")[0].submit()
}
</script>
</body>
</html>
除此之外,你把你的身体放在头上,这可能会给某些浏览器带来麻烦。
答案 2 :(得分:0)
您的提交按钮位于表单标记之外,这就是onsubmit方法未被gettting调用的原因。
答案 3 :(得分:0)
您的代码存在问题。请记住,您必须在<form></form>
标记下放置提交按钮。并始终将JS代码放在<head></head>
部分。
查找下面的代码并尝试希望这对您有用。
<html>
<head>
<script>
function validateForm() {
var firstName = document.getElementById("firstName");
if (firstName.value.length < 6) {
alert("Please enter your first name (6 characters or more)");
firstName.focus();
return false;
}
alert("Thank you for your submission");
return true;
}
</script>
</head>
<body>
<form name="myForm" autocomplete="on" onsubmit="return validateForm();">
<p><label>First name (required) <input type="text" id="firstName"
autofocus="autofocus" /> </label></p>
<input type="submit" name="S1" value="Submit response" />
</form>
</body>
</html>