简体   繁体   中英

selectize.js typescript: Cannot read properties of undefined (reading '0')

I am trying to implement selectize.js inside my project with webpack and typescript.

First I installed selectize.js and related types:

yarn add @selectize/selectize 
yarn add @types/select2 

In my code I inserted this:

require("selectize")();

jQuery(function($){

    $(document).ready(function(){

        $('.classic-select').selectize();
    
    });
    
});

The code compiles correctly but when I go to run it in console I get this error and I don't understand what it refers to:

Cannot read properties of undefined (reading '0')

Can you help me solve this problem?

Thanks in advance Danilo

After several attempts, I figured out how to correctly implement selectize.

First I imported jquery and selectize like this:

import $ from 'jquery';
import 'selectize'; // globally assign select2 fn to $ element

Next I used selectize

jQuery(function($){

    $(document).ready(function(){

        (<any>$('.classic-select')).selectize();
    
    });
    
});

You can also implement it like this

$(() => {
    (<any>$('.classic-select')).selectize();
});

If you compile the code the jquery library will also be imported. If jquery has already been called in your code you can exclude it from compiling through webpack:

externals: {
  jquery: 'jQuery'
}

I hope it will be useful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM