2011-08-04 3 views
0

jQueryの検証を使用すると、ページに多数のフィールドがあり、それらのフィールドの1つだけを満たす必要がある場合は、すべて空白の場合のみエラーを発生させます。すべてのフィールドが空白の場合にのみjQueryで検証する方法

つまり、ユーザーは1つ以上のフィールドを入力できますが、すべてが空白の場合はエラーが発生します。 jQueryの検証でこれを行う方法があるかどうかを知りたい。

答えて

6

これらの行に沿って何かが動作するはずです。

var valid=0; 
$("#myform input[type=text]").each(function(){ 
    if($(this).val() != "") valid+=1; 
}); 

if(valid){ 
    console.log(valid + " inputs have been filled"); 
} 
else { 
    console.log("error: you must fill in at least one field"); 
} 

See a working example here on jsFiddle

0

var name = $('#name').val(); 
    var city = $('#city').val(); 

    if(name == '' && city == '') // this will only fire when both name and city are empty if one of them is not empty than this if condition will not fire 
    { 
     alert('all fields are required'); 
    } 
、これを試してみてください
関連する問題