Friday, 13 September 2013

Cancelling form submission through JavaScript

When doing client-side validation on a web form, there arises a need to cancel the form submission if the user has not provided the data as required by the host website. This can be easily accomplished by invoking the preventDefault method on the 'event' argument passed to the form's 'Submit' event-handler. An example will better illustrate it; so, here it goes:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>Cancelling Form Submission</title>
<style>
    .error {border: 2px solid red;}
    div:last-child {margin-top: 10px;}
</style>
</head>
<body>

<form method="post" action="#">
     
   <div>
        <label for="name">Your name (atleast 3 characters long): </label>
        <input type="text" name="name" id="name" required />
   </div>
   
    <div>
        <button type="submit">OK</button>
    </div>
</form>

<script>
    
    var formElement = document.forms[0];
    formElement.addEventListener("submit", onFormSubmission, false);
    
    function onFormSubmission(e) {
        var textElement = document.getElementById("name");
        if (textElement.value.length < 3) {
            textElement.className = "error";
            e.preventDefault();
        }
    }     
    
</script> 

</body>

</html>

Some people could say that what I have written is nothing new, and is known for ages. They would be very true if they said so. However, my motive behind writing these posts is not to announce any path-breaking discoveries to the world, but to note down some of my learnings so as to reinforce it.

No comments:

Post a Comment