首页 > 解决方案 > 为什么 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);

标签: htmlformsinputrequired

解决方案


所以我首先将输入类型更正为提交

<input type="submit" value="submit" name="submit">

然后在我改变的javascript文件中

submitButton.addEventListener('click',processForm); 

submitButton.addEventListener('form.submit()',processForm);

它似乎工作:)


推荐阅读