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

2

17

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>
Tevere answered 5/8, 2016 at 20:18 Comment(0)
N
45

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

Neufer answered 22/11, 2016 at 16:20 Comment(1)
If you did any event bindings by yourself (not by plug-in) you also have to call the method "off" to unbind those events, example: $('select').off('select2:select');. Docs page: select2.org/programmatic-control/methods#event-unbindingSchiffman
T
8

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');
Teredo answered 2/3, 2020 at 0:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.