Search code examples
javascriptjqueryformbuilder

How to add new generic attribute in jQuery FormBuilder


I'm using jQuery FormBuilder (https://formbuilder.online/) and I need one custom attribute as a Checkbox for every type. So independently from whether it's a textarea, text input, checkbox or similarly - I always want to add the same checkbox as a new attribute.

My options look like this:

options = {
    scrollToFieldOnAdd: false,
    disableFields: ['button', 'file', 'hidden'],
    disabledAttrs: ['access'],
    // Add custom checkbox property to the form
    typeUserAttrs: {
        text: {
            showInGroupDesc: {
                type: 'checkbox',
                label: 'Show in Group Desc.?'
            }
        }
    }
}

Which makes use of typeUserAttrs, unfortunately I have to specify exactly the type of field where I want to add the new attribute showInGroupDesc into.

I do not want to copy/paste this element in typeUserAttrs for every single type - is there a wildcard setting?


Solution

  • Found a solution myself by initializing an Object userAttrs with the new Attribute(s) newAttributes before passing it to typeUserAttrs:

    // New attribute for specified fields 'fields' below
    var newAttributes = {
                showInGroupDesc: {
                    type: 'checkbox',
                    label: 'Show in Group Desc.?'
                }
            };
    var userAttrs = {};
    const fields = ["autocomplete", "checkbox-group", "date", "number", "radio-group", "select", "text", "textarea"];
    fields.forEach(function (item, index) {
        userAttrs[item] = newAttributes;
    });
    
    // Initialise the form builder
    options = {
        // ... All your options here ...
        typeUserAttrs: userAttrs
      };