How do I set value attribute to name rather than ID


#1

I am trying to implement a tagging feature in Laravel application.
Implementation consist of tag cloud which is fetched using ajax request to recommend tags also there is an option to create new tag if a tag is not present. In backend I want to get all the tag names.
Steps to produce result:
JS code

    $('#tags').select2({
        tags: true,
        tokenSeparators: [',', ' '],
        minimumInputLength: 2,
        ajax: {
            url: '{{ route("tags.search") }}',
        },
        placeholder: 'Search for a category',
        data: function (params) {
                    return {
                        q: $.trim(params.term)
                    };
                },
                processResults: function (data) {
                    console.log(data);
                    return {
                        results: data
                    };
            },
        cache: true
    });

HTML code

<div class="form-group col-sm-12 col-md-6">
                                <label for="tags">Tags</label>
                                <select class="js-example-basic-multiple select2-purple" name="tags[]" multiple id="tags" style="width: 100%">
                                        <option value="AL">PHP</option>
                                        <option value="WY">JAVA</option>
                                </select>
</div>

Requset object outupt:
tags: array['0'->'1','1'->'test']
Values: 0->1(oldtag) is for ajax returned value, 1->test for new value not present in cloud tag
Expected Output
tags: array['0'->'oldtag','1'->'newtag']


#2

So it looks like your code is working the way you want it to for new tags (the value in the tags array is the text of the new tag you created). However, for existing tags retrieved via AJAX, you’re getting a numeric value listed of the selected item’s text.

The fix is to use the processResults callback to return a data array that contains the items’ text values as both their “id” and “text” fields. As long as the tag values from the AJAX response are unique and not blank or empty, they can be used as the “id” attribute as well as the “text” value.