Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle " The select2('destroy') method was called on an element that is not using Select2"

I am using ui-select2 and trying to open new page on click of edit button. I am seeing some strange issue. First time when I am opening the new page it is opening fine, but when I am cancelling it and again opening the same page, by clicking edit, it is giving me following error:

select2.full.min.js:3 The select2('destroy') method was called on an element that is not using Select2
angular.js:13708 TypeError: Cannot read property 'destroy' of undefined
at n.a.fn.select2 (select2.full.min.js:3)
at HTMLSelectElement.<anonymous> (select2.js:175)
at HTMLSelectElement.dispatch (jQuery-2.1.4.min.js:3)
at HTMLSelectElement.r.handle (jQuery-2.1.4.min.js:3)
at Object.trigger (jQuery-2.1.4.min.js:3)
at n.triggerHandler (jQuery-2.1.4.min.js:3)
at Function.pa.fn.on.pa.cleanData (angular.js:1865)
at n.remove (jQuery-2.1.4.min.js:3)
at angular.js:5504
at Object.push (angular.js:5085)

By reading this msg, it seems I will have to define destroy method but I am not getting how to define destroy method in my controller and how to call on cancel button (cancel method) call.. Following are the code snippet for select:

<select ui-select2 class="form-control input-lg" ng-model="cityId" ng-change="loadLocality()">
                                <option ng-repeat="city in cities|orderBy:'name'|filter:'ACTIVE':true" value="{{city.id}}">{{city.name}}</option>
                            </select>
like image 852
Madhusudan Sahu Avatar asked Aug 05 '16 20:08

Madhusudan Sahu


People also ask

How do I create a select2 dynamically?

Select2 jQuery plugin is easy to add on the <select > element. Need to call the select2() method on the selector to initialize. If you adding select2 on a class or select element and when you add an element dynamically then select2 is not initialized on that element.

How do I assign a value to select2?

To dynamically set the "selected" value of a Select2 component: $('#inputID'). select2('data', {id: 100, a_key: 'Lorem Ipsum'}); Where the second parameter is an object with expected values.


2 Answers

Use a simple check for select2 like this:

if ($('select').data('select2')) {
   $('select').select2('destroy');
 }

I found the code in a GitHub Issue https://github.com/aldeed/meteor-autoform-select2/issues/44

like image 63
Mario Naether Avatar answered Sep 19 '22 05:09

Mario Naether


From the official documentation: https://select2.org/programmatic-control/methods#checking-if-the-plugin-is-initialized

You can check if your select has the class '.select2-hidden-accessible'.

$("select.select2-hidden-accessible").select2('destroy');
like image 24
Niko Avatar answered Sep 19 '22 05:09

Niko