H. Pauwelyn
H. Pauwelyn

Reputation: 14330

Show error after button click Javascript

After my button click, I would check if my text fields are not empty. My check works, but if I show my message it's show for a few seconds. Probably the duration of my button click. Here is some code I've tried.

<form>
    <div id="errorblock">
        <p id="errortext">Error.</p>
    </div>
    <!-- here are my input fields-->

    <button>Send</button>
</form>

This is where I add my event listener after initialisation of the page:

document.getElementsByTagName("button")[0].addEventListener("click", function(){
    sendEmail();
});

function sendEmail() {

    //check if all fields are fill in. If not do this code;
    document.getElementById("errortext").innerHTML = "Fill in all the fields please.";

    var errorblock = document.getElementById("errorblock");       
    errorblock.style.visibility = "visible";
    errorblock.style.height = "46px";
}

Can anyone help me? Thanks

Upvotes: 1

Views: 3551

Answers (1)

dfsq
dfsq

Reputation: 193301

By default HTMLButtonElement has type="submit". It means that on button click the form is submitted. You need to make sure you prevent this submission in case of errors in the form. For example by calling preventDefault methods of the event object:

document.getElementsByTagName("button")[0].addEventListener("click", function (e) {
    if (!sendEmail()) {
        e.preventDefault();
    }
});

function sendEmail() {

    //check if all fields are fill in. If not do this code;
    document.getElementById("errortext").innerHTML = "Fill in all the fields please.";

    var errorblock = document.getElementById("errorblock");
    errorblock.style.visibility = "visible";
    errorblock.style.height = "46px";

    // if there are errors return false
    // return true if input is correct
    return false;
}

Also I recommend to listen onsubmit event on the form instead of button click event:

document.querySelector("form").addEventListener("submit", function (e) {
    if (!sendEmail()) {
        e.preventDefault();
    }
});

Upvotes: 5

Related Questions