2015-12-02 5 views
5

フォームにまだ入力されていない必須フィールドの配列/リストを表示して操作するための賢明な方法を見つけようとしています。この情報をユーザーに提示し、ユーザーが通過してフィールドを(進行状況の一種として)入力する際に​​リストから各項目を削除します。どのようにこれを処理するための最良の考え?必要なフィールドに基づいて配列を構築し操作する

私は、次の線に沿って何かを考えています:配列内のアイテムを削除/値をチェックし、それに応じて追加入力イベントで

var reqFields = []; 

jQuery('label.required').each(function() { 
    console.log(jQuery(this).text()); 

    reqFields.push(jQuery(this).text()); 
}); 

jQuery('.custom-field').on('input', function() { 
    if (jQuery('.required-entry').filter(function() { 
      return this.value.length === 0; 
     }).length === 0) { 
     // Remove this from the list/array 
    } else { 

    } 
}); 

答えて

1

var reqFields = []; 

jQuery('label.required').each(function() { 
    console.log(jQuery(this).text()); 
    reqFields.push(jQuery(this).text()); 
}); 

jQuery('.custom-field').on('input', function() { 
    if (this.value) { 
     // Remove this from the list/array 
     reqFields.splice(jQuery(this).index(),1); 
     // jQuery(this).index() havent tried, else just compute index some other way 
    } else { 
     // add back if cleared out 
     reqFields.push(jQuery('label.required').eq(jQuery(this).index()).text()); 
    } 
}); 
1

は、代わりのエントリを削除するので、必要なフィールドの入力に変化がありますたびに、あなたは、単に空の入力で必要なフィールドのリストにreqFields配列を再度割り当てることができます。

var reqFields = []; 

jQuery(function() { 
    jQuery('.requiredFields').on('input', function() { 
    reqFields = jQuery('.requiredFields').filter(function() { 
     return this.value.length === 0; 
    }); 
    }); 
}); 
1

クラスrequired-entry持つすべてのフィールドをループにinputeachを使用して怒鳴る、この基本的な例を確認し、最後にフィールドが必要とされているユーザーに通知する#msgにまたがるメッセージを追加する空のものをご確認ください。

これが役に立ちます。


$('.required-entry').on('input', function() { 
 
    $('#msg').empty(); 
 
    
 
    $('.required-entry').each(function() { 
 
     if ($(this).val().length == 0) 
 
      $('#msg').append('Field <b>'+$(this).prev('label').text()+'</b> is required.<br/>'); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label class='required'>First Name</label> 
 
<input type='text' id='first_name' name='first_name' class='required-entry' required/> 
 
<br/> 
 
<label class='required'>Last Name</label> 
 
<input type='text' id='last_name' name='last_name' class='required-entry' required/> 
 
<br/> 
 
<label class='required'>Email Address</label> 
 
<input type='text' id='email' name='email' class='required-entry' required/> 
 
<hr/> 
 
<br/> 
 
<span id='msg'></span>

関連する問題