XF 2.2 Tags / token-input / I want to apply new tags via JavaScript

Scandal

Well-known member
Hello all! :)

Well, I have the following template code:
HTML:
                            <xf:if is="$xf.visitor.getWhitelistTags() && $xf.visitor.getIsTagWhitelistEnabled()">
                                <div style="margin-top: 10px;">
                                    <span class="js-tagList">                       
                                        <xf:foreach loop="$xf.visitor.getWhitelistTags()" value="$t">
                                            <a style="text-decoration: none;" href="javascript:void(0)" class="tagItem" dir="auto" onclick="sc_insert_tag('{$t}')">{$t}</a>                               
                                        </xf:foreach>
                                    </span>                                   
                                </div>
                                <xf:js>
                                    function sc_insert_tag(text)
                                    {   
                                        $('.select2-search__field').val(text + ',').keyup();
                                    }
                                </xf:js>
                            </xf:if>
It works as intended if you try to click a tag item (sc_insert_tag('{$t}')) immediately after page-load, but if you try to add manually (via your keyvoard) some tags (like the aaaa) and then click one of the whitelisted tags, it does not applied as token, it just adds the text:
token_input.webp

Any idea how to fix it?
Maybe you as javascript experts to provide me an example of xF2 js core normalized way to add the tag on the input-token field? :)

Thank you very much!
 

This should work for you:
HTML:
<a data-xf-click="insert-select2" data-value="Your value" data-text="Value label"></a>
JavaScript:
XF.InsertSelect2 = XF.Click.newHandler({
    eventNameSpace: 'XFInsertSelect2',
    options: {
        selector: '< form | .js-tokenSelect',
        text: null,
        value: ''
    },

    init () {
        this.$select = XF.findRelativeIf(this.options.selector, this.$target);
    },

    click () {
        const option = this.getOption();

        // check if option already exists
        // add option to select if not
        if (! this.$select.find(`option[value="${option.value}"]`).length) {
            this.$select.append(option);
        }

        let options = this.$select.val();
        options ??= [];
        options.push(option.value);

        // unique options
        options = [...new Set(options)];

        this.$select.val(options).trigger('change');
    },

    getOption () {
        return new Option(
            this.options.text || this.options.value,
            this.options.value
        );
    }
})

XF.Click.register('insert-select2', 'XF.InsertSelect2');
 
Back
Top Bottom