Check if inputs are empty using jQuery

前端 未结 18 1339
灰色年华
灰色年华 2020-11-22 09:14

I have a form that I would like all fields to be filled in. If a field is clicked into and then not filled out, I would like to display a red background.

Here is my

18条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 09:34

    Doing it on blur is too limited. It assumes there was focus on the form field, so I prefer to do it on submit, and map through the input. After years of dealing with fancy blur, focus, etc. tricks, keeping things simpler will yield more usability where it counts.

    $('#signupform').submit(function() {
        var errors = 0;
        $("#signupform :input").map(function(){
             if( !$(this).val() ) {
                  $(this).parents('td').addClass('warning');
                  errors++;
            } else if ($(this).val()) {
                  $(this).parents('td').removeClass('warning');
            }   
        });
        if(errors > 0){
            $('#errorwarn').text("All fields are required");
            return false;
        }
        // do the ajax..    
    });
    

提交回复
热议问题