Skip to main content
Oct 16, 2013

One of the most used logic related to submitting a form is preventing sumbission if a field is empty. In this example we'll provide examples with source code how to prevent form submit in case of empty field. The main trick here is using .preventDefault() function to stop the submission.

<form method="post" action="">
    <input id="testfield" type="text" />
    <input id="submit" type="submit" value="Submit">
</form>

Here is jQuery code that will prevent submitting the form if the field is empty and it will display message, too:

$(document).ready(function() {
    $('#submit').click(function(event){
        var data = $('#textbox').val();
        var length = data.length;
        if(length < 1) {
            event.preventDefault();
        }
    });
});