[JS] Select2 problems setting values by default

Published 1 week ago by Lina

Hi friends,

I am trying to use the select2 lib (https://select2.org/data-sources/formats) to create an input to add tags associated with a Posts of the Blog, but when I charge the page the values of the tags are not appearing in the input like a introduced values.

https://gyazo.com/6359955a1ef17ce85c8d7409fb336298

        <div class="form-group">
        <label for="tags" class="control-label">Tags</label>
             <select id="tags" name="tags[]" class="form-control" multiple="multiple">
             </select>
        </div>
     
        $('#tags').select2({
    // What values should I do add to set values by default?
            multiple: true,
            results: {
                  "id": 3,
                  "text": "Option 3",
            },
            tokenSeparators: [','],
            ajax: {
                url: '{{ url("getTagsSelect2") }}',
                dataType: 'json',
                data: function(params) {
                    return {
                        term: params.term
                    }
                },
                processResults: function (data, page) {
                    return {
                        results: data
                    };
                },
            },
        });

I tired this but is not working:

        $('#tags').select2({
           multiple:true,
           ajax:{}}).select2({"data": 
        [{"id":"2127","text":"Henry Ford"},{"id":"2199","text":"Tom Phillips"}]});

Thanks for your help

Sign In or create a forum account to participate in this discussion.