我正在运行这个问题,我正在点击提交按钮,但它没有显示像“fname,email,message”这样的特定条目是必需的。
我尝试过不同的方法,比如在输入标签中加入“required”属性,但这里也发生了同样的事情。
这是contact.html
文件:
<script defer src="script.js"></script>
<div id="error"></div>
<div class="con"><div class="he"><h1>Contact Us</h1><br>
<p>Please feel free to contact us with any questions you may have around our coaching or online analysis. </p></div> </div> -->
<div class="con2"> <div class="form"><form class="form" name="myform" method="GET">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" class="name1">
<label for="lname"class="n">Last name:</label>
<input type="text" id="lname" name="lname" class="name2"><br>
<label for="email">Email:</label><br>
<input type="text" id="mail2" name="email"class="mail"><br>
<label for="comment">Message or Comment:</label><br>
<textarea name="comment" rows="10" cols="30"class="para">
</textarea><br>
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
script.Js
文件:
const name=document.getElementsByClassName('name1')
const name2=document.getElementsByClassName('name2')
const mail=document.getElementsByClassName('mail')
const para=document.getElementsByClassName('para')
const form=document.getElementsByClassName('form')
const errorElement=document.getElementById('error')
form.addEventListener('submit' , (e)=>{
let messages = [] if (name1.value == =''|| name1.value == null) {
messages.push('Name is required')
}
if (mail.value == =''|| mail.value == null) {
messages.push('Mail is required')
}
if (para.value == =''|| para.value == null) {
messages.push('Message is required')
}
if (messages.length > 0) {
e.preventDefault() errorElement.innerText = messages.join(', ')
}
})
1条答案
按热度按时间ruyhziif1#
请为
<form>
元素使用id
,因为class="form"
对于<form>
标记和<div>
标记都是重复的,<div>
标记包裹着<form>
。我已经清理了您的代码,请尝试以下操作: