Bham
Bham

Reputation: 319

Jquery count all empty fields

Is there a way in jquery to count all empty inputs and textareas in a form, for the following types

checkbox, date, datetime, email, month, number, radio, tel, text

because every form has a js variable maxInput. if maxInput is 6 (form has 6 inputs) then if you count the inputs and it is 6 i know that all is filled. Does anybody knows how to complete this.

Upvotes: 4

Views: 1603

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39966

Suppose all inputs has a class named: yourClass then this may help you:

$('.yourClass').filter(function(){
return !$(this).val();
}).length;

Upvotes: 5

Ryan Neuffer
Ryan Neuffer

Reputation: 792

This should work for a variable/dynamic number of the inputs you specified given a form with class 'test-form'. Just be sure you set value="" on the default option of your selects. Checking if the radio button group is unselected is a little trickier:

var emptyTextCheckboxAndSelect = $('.test-form input, .test-form select').filter(function(){

    if($(this).attr('type') === "radio"){
        return false;//we'll check for empty radio groups elsewhere        
    }

    if($(this).attr('type') === "checkbox"){
        return !$(this).prop("checked");
    }

    return !$(this).val();//this only works for select if default option explicitly sets value=""

}).length;


var radioNameHash = {},
    uncheckedRadioButtonGroups = 0;

$('.test-form input[type="radio"]').each(function(i, radioButton){

    if(radioNameHash[$(this).attr('name')] === undefined){
        uncheckedRadioButtonGroups++;
        radioNameHash[$(this).attr('name')] = true;
    }

    if($(this).prop("checked") === true){
        uncheckedRadioButtonGroups--;
    }
});

var totalUnfilledFields = emptyTextCheckboxAndSelect + uncheckedRadioButtonGroups;

alert(totalUnfilledFields);

Here's the fiddle: https://jsfiddle.net/qLedcr82/1/

As an aside, it's typically a best practice to set a default value for radio button groups which would render that part of the solution useless.

Upvotes: 2

Related Questions