Sam Skirrow
Sam Skirrow

Reputation: 3697

jQuery check if form input is empty except for one

I have a form where all fields are required except for one. This field has a class "discount". I am using this code to check through the form on submission to see if there are any empty fields. Is there a easy way I can add the input ".discount" as an exception to this code?

$("#quote_form").submit(function(){
var isFormValid = true;

$("input, select").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 highlighted fields");

return isFormValid;
});

Upvotes: 1

Views: 858

Answers (2)

palaѕн
palaѕн

Reputation: 73906

If possible add a ID to the field and then you can do like:-

$('input, select').not('#fieldID').each(function(){.....

using a class inside the .not() method is not a good idea here, since there might be few more fields with the same class name too. But you requirement here is to just remove a specific field from the validation code logic.

In case, you have only one field with that class you can then use the below code like:

$('input, select').not('.discount').each(function(){.....

Upvotes: 1

Anton
Anton

Reputation: 32581

You can use .not() like this

$("input, select").not('.discount')

Upvotes: 2

Related Questions