4

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.

2 Answers 2

5

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

$('.yourClass').filter(function(){
return !$(this).val();
}).length;
Sign up to request clarification or add additional context in comments.

4 Comments

Does this also count radio and select boxes?
Select, yes—checkbox and radio unlikely. Also keep in mind this will return a false positive if the value in the field is the number 0.
$( 'input[type=radio]' ) will get all radio buttons.
Finding how many radio button groups are unselected is a bit more difficult than that.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.