goldlife
goldlife

Reputation: 1989

Update / add values to multiple select2 field after ajax call

I try to add values to a select2 (multiple select) field after performing an ajax call. I search for the solution and find this question: Dynamically add item to jQuery Select2 control that uses AJAX

This is my JS:

$scope.addProjectType = function(name) {
        $http.post('/ajax/projecttype/addprojecttype', {
            name: name
        }).success(function(data, status, headers, config) {
            $("#projectTypes").select2('data', {
                id: 1, name: 'test'
            })
        });
    }

It's all fine, but while performing the ajax success function this gives me the error

Error: state_id.split is not a function format@http://ttos2.localhost/vendor/assets/global/js/plugins.js:269:31 i<.addSelectedChoice@http://ttos2.localhost/vendor/assets/global/plugins/select2/select2.min.js:6:54786 i<.updateSelection/<@http://ttos2.localhost/vendor/assets/global/plugins/select2/select2.min.js:6:53377

What I am doing wrong here?

Upvotes: 1

Views: 1259

Answers (1)

goldlife
goldlife

Reputation: 1989

This it how it works ...:

$scope.addProjectType = function(name) {
            $http.post('/ajax/projecttype/addprojecttype', {
                name: name
            }).success(function(data, status, headers, config) {
                $("#projectTypes").append('<option value="' + data.id + '">' + data.name + '</option>');

                // get a list of selected values if any - or create an empty array
                var selectedValues = $("#projectTypes").val();
                if (selectedValues == null) {
                    selectedValues = new Array();
                }
                selectedValues.push(data.id);   // add the newly created option to the list of selected items
                $("#projectTypes").val(selectedValues).trigger('change');   // have select2 do it's thing
            });
        }

Upvotes: 2

Related Questions