Jquery form submit to check empty fields

2019-01-21 17:16发布

How could I use jquery to check if text-fields are empty when submit 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.

8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-21 17:54

you need to add a handler to the form submit event. In the handler you need to check for each text field, select element and password fields if there values are non empty.

$('form').submit(function() {
     var res = true;
     // here I am checking for textFields, password fields, and any 
     // drop down you may have in the form
     $("input[type='text'],select,input[type='password']",this).each(function() {
         if($(this).val().trim() == "") {
             res = false; 
         }
     })
     return res; // returning false will prevent the form from submitting.
});
查看更多
冷血范
3楼-- · 2019-01-21 18:00

You can do this:

//  Bind the event handler to the "submit" JavaScript event
$('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

查看更多
登录 后发表回答