【发布时间】:2020-02-22 13:09:10
【问题描述】:
我想在提交之前尝试验证输入,因此我在输入末尾使用了 required 属性,但它不起作用,我已经尝试了一些推荐的解决方案,例如将输入包装在表单标签中或尝试关闭 input () 的标签,但是当我提交带有空输入的表单时,它仍然正常提交并且没有声明必填字段。 我将不胜感激任何帮助,谢谢! 这是我的代码的一部分
<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);
【问题讨论】:
-
你用的是什么浏览器?是否涉及任何 Javascript?
-
我正在使用 Opera ,是的,我正在处理一个 javascript 页面以及其他链接到引导样式的页面
-
那么,表单是通过 Javascript 提交的吗?
-
是的,通过单击 sumbit 按钮,我调用了一个获取提交信息并继续的函数 (submitButton.addEventListener('click',processForm);
-
那么您显然是在用自己的表单行为替换表单行为,并且还需要在 Javascript 中复制所需的逻辑。或者不是挂钩按钮单击事件,而是挂钩表单的
submit事件,这可能仅在验证后触发(现在不确定我的头顶)。