Skip to content Skip to sidebar Skip to footer

Adobe Pdf Javascript For Forms: Grouping Conditions From If...else Statement

I am designing forms in PDF and validating user input using JavaScript and depending on the user selection different labels appear on the document. Please refer to my sample code b

Solution 1:

What about something like this? It may need some adjustments and I haven't tested, but basically you want to create a data structure that will allow you to generically handle every scenarios the same way.

Using objects as maps here rather than arrays to hold countries is just an optimization that would make the country lookup faster, but it's probably not necessary.

var fieldKeys = ['sugar', 'corn', 'wheet', 'potatoes'];
var fields = fieldKeys.reduce(function(res, type) {
    res[type] = getField(type + 'label');
    return res;
}, {});

var countriesByType = {
    sugar: {
        'Afghanistan': true,
        'Albania': true
    },
    corn: {
        'Australia': true,
        'Belgium': true
    }
};

updateFieldsVisibility({ type: 'corn', country: 'Albania' });

functionupdateFieldsVisibility(selection) {
    var countries = countriesByType[selection.type];

    hideOtherTypeFields();

    fields[selection.type].display = display[countries[selection.country]? 'visible' : 'hidden'];

    functionhideOtherTypeFields() {
        fieldKeys
            .filter(function(field) {
                return field != selection.type;
            })
            .forEach(function(field) {
                fields[field].display = display.hidden;
            });
    }
}

As you can see for sugar and wheet & corn and potatoes I have the same sequence of countries, so I was hoping to group them somehow to prevent me from repeating them again and again

You could just do the following and use the same approach as above:

varsugarAndWheatCountries= {
    'Afghanistan':true,
    'Albania':true,
    ...
};varcornAndPotatoesCountries= {
    'Australia':true,
    'Belgium':true,
    ...
};varcountriesByType= {
    sugar:sugarAndWheatCountries,
    wheat:sugarAndWheatCountries,
    corn:cornAndPotatoesCountries,
    potatoes:cornAndPotatoesCountries
};

To make the code smaller you may create maps dynamically from arrays:

var sugarAndWheatCountries = mapFromStringArray(['Afghanistan', 'Albania', ...]);


functionmapFromStringArray(arr) {
    return arr.reduce(function (acc, str) {
        acc[str] = true;
        return acc;
    }, {});
}

Post a Comment for "Adobe Pdf Javascript For Forms: Grouping Conditions From If...else Statement"