Search code examples
javascriptjqueryjquery-select2jquery-select2-4

Select2, append doesn't show the title


so I had this problem with select2 autocomplete box, when I'm trying to create the object to the box, it is creating fine, but the name of the object isn't showing in the box and the only thing is showing is "X" to clear the object.

The main focus of the box is to set the values from the database to edit(add, remove etc.) it later. The way I want to do it is first get object from database and then create it in the select2 box.

Here's my javascript file:

$('#recipefield').select2({
        id: function(data){return data.id;},
        maximumSelectionLength: 5,
        minimumSelectionLength: 3,
        ajax: {
            url: function () {
                return getTypedAutoCompleteUrl();
            },
            dataType: 'json',
            processResults: function (data) {
                  return {
                    results: data
                  };
                }
        },
        templateResult: formatState,
        templateSelection: formatState
    });
});

function getTypedAutoCompleteUrl() {
    return '/api/v1/recipe/' + $('#menutype').val();
}

function formatState (state) {
    if (!state.id) {
        return state.text;
    }
    return state.title;
}

And that's what I'm using to add object to the box:

var data = {
    id: 1,
    text: 'text'
};
var newOption = new Option(data.text, data.id, true, true);
$('#recipefield').append(newOption).trigger('change');

So the box looks like this after adding object to it:
adding object to it

And here is what it looks like when I select object manually:
select object manually


Solution

  • So, finally I did make it work, maybe it will be useful for someone.

    Created this function.

    function recipeHelper(){
        var recipeList = $("#recipefield").select2("data");
        for(i=0; i<recipeList.length; i++){
            var recipeObject = recipeList[i];
            recipeObject.name = recipeObject.text;
        }
        $("#recipefield").trigger('change');
    }
    

    The "recipeHelper" function is called in the

    $(document).ready(function() {
        ...
        recipeHelper();
    });
    

    Hope it will help somebody.