Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if input empty on submit

I've been looking around for a solution to this, but can't seem to find any examples that work for me. Here's what I've got so far:

$("#register-form").submit(function(){
            if($(".required input").val() == '') {
                alert("Please fill in all the required fields (indicated by *)");
                $(".required").addClass('highlight');
                // $('input[type=submit]', this).attr('disabled', 'disabled');
                return false;
            }
        });

For some reason, when I submit the form with none of the required fields filled in (there are two), then it works, but if one of them is filled out, it doesn't.

Any ideas why?

Thanks

osu

like image 660
Osu Avatar asked May 04 '11 16:05

Osu


People also ask

How check input box is empty in jQuery?

To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.

How do you validate input in HTML?

To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.


1 Answers

The problem with your code is that you're only testing the first field you've got flagged as required. $(".required input") only returns the first input in your form that matches that selector.

This loops through all the inputs in the form that are flagged required (according to your selector). If it finds one with a value of '' then it sets the submit function to return false and highlights the blank fields. It also removes the highlight class from fields that are now valid but were previously invalid in an early form submit attempt.

$("#register-form").submit(function(){
    var isFormValid = true;

    $(".required input").each(function(){
        if ($.trim($(this).val()).length == 0){
            $(this).addClass("highlight");
            isFormValid = false;
        }
        else{
            $(this).removeClass("highlight");
        }
    });

    if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");

    return isFormValid;
});
like image 196
Ryan Avatar answered Sep 20 '22 20:09

Ryan