Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build and manipulate array based on required fields populated

I'm trying to figure out a sensible way to display and manipulate an array/list of required fields which are yet to be populated in a form - this is just so i can output this info to the user and remove each item from the list as the user goes through and populates the fields (as a sort of progress indicator). Any thoughts on how best to handle this?

I'm thinking of something along the lines of 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 {

    }
});
like image 981
bsod99 Avatar asked Oct 18 '22 21:10

bsod99


2 Answers

On input event check the value and accordingly add/remove item in 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());
    }
});
like image 192
vinayakj Avatar answered Oct 21 '22 23:10

vinayakj


Instead of removing the entries, every time there's a change in input of the required fields, you can simply re-assign 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;
    });
  });
});
like image 45
John Bupit Avatar answered Oct 21 '22 23:10

John Bupit