html - 为什么 html 中的 required 属性不起作用?
问题描述
我想在提交之前尝试验证输入,因此我在输入末尾使用了 required 属性,但它不起作用,我已经尝试了一些推荐的解决方案,例如将输入包装在表单标签中或尝试关闭标签的输入(),但是当我提交我的表单时输入为空,它仍然正常提交并且没有声明必填字段。我将不胜感激任何帮助,谢谢!这是我的代码的一部分
<form id="form" style="background-color:honeydew ;" class="container text-center">
<div><br><h2> Contact Us </h2></div>
<div id="contact">
<div>
<label> Name</label>
<input type="text" placeholder="Your name " name="name" required/>
</div>
<br>
<div>
<label> Email</label>
<input type="email" placeholder="name@gmail.com" name="email" name="email">
</div>
<br>
<div>
<label> Message</label>
<input type="text" style="height:50px;" name="message">
</div>
<br>
<div><input type="button" value="submit" name="submit"><br></div>
<br>
</div>
<br>
</form>
这是链接到它的javascript文件:
//we take informations subbmitted by user from the form and we replace the form with a reply
//containing these pieces of information on the click on the submit button
var form=document.getElementById('form'),
contactForm=document.getElementById('contact'),
submitButton=contactForm.children[6].children[0];
var processForm= function(){
name=document.getElementsByName('name')[0].value,
email=document.getElementsByName('email')[0].value,
sitereplyText=document.createTextNode('this is a initialiazing value'),
sitereplyEl=document.createElement('p');
mytext= 'Hey '+name+'! Thanks for your message :) We will email you back at '+email;
sitereplyText.nodeValue=mytext;
sitereplyEl.appendChild(sitereplyText);
form.replaceChild(sitereplyEl,contactForm);
}
submitButton.addEventListener('click',processForm);
解决方案
所以我首先将输入类型更正为提交
<input type="submit" value="submit" name="submit">
然后在我改变的javascript文件中
submitButton.addEventListener('click',processForm);
至
submitButton.addEventListener('form.submit()',processForm);
它似乎工作:)
推荐阅读
- css - unicode-range 如何与连字一起使用?
- webpack - 如何使用 webpack 4 启动电子主进程并启用热模块替换?
- c - 为什么我的 Timer2 中断不起作用?我是否缺少任何注册配置?
- python - 如何让我的程序在绘制线性方程时要求用户输入
- python - 在 AWS S3 中解密对象而不将其下载到本地系统
- javascript - 刷新时未加载新数据
- python - 如何检测 Firebase Firestore 数据库中的实时监听器错误?
- ssh - Cygwin key_load_public:格式无效
- javascript - 使用带有选择的 onclick 事件
- python - 如何测试我用 Keras 创建的模型