2015-07-19 85 views
2

有没有办法在jQuery来计算所有空输入和文字区域的形式,以下类型的jQuery的统计所有空字段

复选框, 日期, 日期时间, 电子邮件, 月, 号, radio, tel, text

因为每个窗体都有一个js变量maxInput。 如果maxInput是6(表单有6个输入) 那么如果你计算输入,它是6我知道所有填充。 有谁知道如何完成这个。

回答

1

这应该给予带班的考试形式“形式指定的输入变量/动态数工作。只要确保在选择的默认选项上设置了value =“”。检查是否单选按钮组未选中有点麻烦:

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); 

这里的小提琴:https://jsfiddle.net/qLedcr82/1/

顺便说一句,这是典型的设置为单选按钮组这将使默认值的最佳实践那部分解决方案毫无用处。

2

假设所有inputs有一个名为类:yourClass那么这可能会帮助您:

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

这是否也计算无线电和选择框? – Bham

+0

选择,是 - 复选框和无线电不太可能。另请注意,如果字段中的值为数字0,则会返回误报。 –

+0

它不会。 https://jsfiddle.net/qLedcr82/ –