简体   繁体   中英

Can't stop function execution when submitting a form with required fields not filled

it's probably a simple logic problem and I'm probably doing something wrong but I can't find why.

When my form is submitted i'm using a little API to send a mail with some JS code (emailJS). I can make the html say "Please fill out this field" but the mail is still sended.

I tried with preventDefault and stopImmediatePropagation :

HTML

<label for="watts1">Device 1:</label>
<input type="number" required/>
<input type="submit" id="submitButton" value="Send form"/>

JS

document.getElementById("submitButton").addEventListener("click", function (e) {
    // e.preventDefault();
    // e.stopImmediatePropagation();

    
    form.subject = `${form.name} ${form.surname} ...`
    form.body = `${form.name} ${form.surname} ...`


    Email.send({
        SecureToken: "***",
        To: "***",
        From: `***`,
        Subject: `${form.subject}`,
        Body: `${form.body}`,
    }).then((message) => alert(message));
});

I'm pretty new to coding, I found much solutions on different websites for any previous issue but here I'd like to find an easy way to make it instead of weird solutions that I can't yet understand.

Thanks in advance !

HTML5 required validation normally works on submit events

If you do not want a form, you can check the validity of the field:

Note I changed the button to type="button"

 document.getElementById("sendButton").addEventListener("click", function(e) { if (document.getElementById("number").checkValidity()) { console.log("sending"); // never reached if number is empty /* Email.send({ SecureToken: "***", To: "***", From: `***`, Subject: `${form.subject}`, Body: `${form.body}`, }).then((message) => alert(message)); */ } });
 <label for="watts1">Device 1:</label> <input type="number" required id="number" /> <input type="button" id="sendButton" value="Send form" />

Using form submit event

 document.getElementById("formID").addEventListener("submit", function(e) { e.preventDefault(); // necessary here console.log("sending"); // never reached if number is empty /* Email.send({ SecureToken: "***", To: "***", From: `***`, Subject: `${form.subject}`, Body: `${form.body}`, }).then((message) => alert(message)); */ });
 <form id="formID"> <label for="watts1">Device 1:</label> <input type="number" required/> <input type="submit" id="submitButton" value="Send form" /> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM