为什么html中的必填属性不起作用?

问题描述 投票:0回答:1

我想在提交之前尝试验证输入,因此我在输入末尾使用了必需的属性,但是它不起作用,并且我已经尝试了一些推荐的解决方案,例如将输入包装在表单标签中或尝试关闭输入()的标记,但是当我使用空输入提交表单时,它仍会正常提交,并且未声明必填字段。我将不胜感激,谢谢!这是我的代码的一部分

<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="[email protected]" 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);
html forms input required
1个回答
0
投票
所以我首先将输入类型更正为提交

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

然后在我更改的javascript文件中

submitButton.addEventListener('click',processForm);

to

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

并且似乎起作用:)
© www.soinside.com 2019 - 2024. All rights reserved.