How to check if text fields are empty on form submit using jQuery?

conmen picture conmen · May 15, 2013 · Viewed 158.5k times · Source

How could I use jQuery to check if text-fields are empty when submitting without loading login.php?

<form action="login.php" method="post">
    <label>Login Name:</label>
    <input type="text" name="email" id="log" />
    <label>Password:</label>
    <input type="password" name="password" id="pwd" />
    <input type="submit" name="submit" value="Login" />
</form>

Thanks.

Answer

palaѕн picture palaѕн · May 15, 2013

You can bind an event handler to the "submit" JavaScript event using jQuery .submit method and then get trimmed #log text field value and check if empty of not like:

$('form').submit(function () {

    // Get the Login Name value and trim it
    var name = $.trim($('#log').val());

    // Check if empty of not
    if (name  === '') {
        alert('Text-field is empty.');
        return false;
    }
});

FIDDLE DEMO