Creating and managing an array based on completed fields

I'm trying to find a reasonable way to display and manage an array / list of required fields that are not yet filled in the form - it's just that I can display this information to the user and remove each item from the list when the user goes through and fills the fields (as a kind of indicator progress). Any thoughts on how best to deal with this?

I am thinking of something like the following:

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 { } }); 
+5
source share
3 answers

At the input event, check the value and, accordingly, add / remove an element in the array.

 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
source

Instead of deleting entries, every time a change in the input of the required fields occurs, you can simply reassign the reqFields array to the list of required fields with empty input.

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

See the example below, using each on input , to see all fields with the required-entry class and check for empty, to finally add a message to span #msg to tell the user which fields are needed.

Hope this helps.


 $('.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> 
+1
source

Source: https://habr.com/ru/post/1237286/


All Articles