forms – Why does required attribute in html doesn't work?-ThrowExceptions

Exception or error:

I wanted to try and verify input before being submitted therefore I used the required attribute at the end of input, but it’s not working and I’ve already tried some of the recommended solution like wrapping the input in form tag or trying to close the tag of input () but when i submit my form with an empty input it stills submited normally and doesn’t declare a required field .
I would appreciate any help, thank you!!
this is a part of my code

<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>

and this is the javascript file linked to it :

//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);
How to solve:

So i firstly corrected the input type into submit

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

then in the javascript file i changed

submitButton.addEventListener('click',processForm); 

to

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

and it seems to work 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *