Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as

Uncaught TypeError: Cannot read property 'replace' of null
.

Although using an ajax source for data works, it does not filter the data upon typing. As mentioned here, matching only functions effectively with array data:

The matcher feature can only be used with locally provided data (e.g., via an array). When a remote dataset is utilized, Select2 assumes that the returned results have been pre-filtered on the server side.

To address this, I'm now constructing an array from the ajax GET call: $.getJSON('/api/skills/all'), and then utilizing this as the datasource in my select2 setup:

$(document).ready(function() {

    // Pre-populate search bar with selected items
    var skillsSelect = $('.select2-input');
    $.getJSON('/api/skills/user/')
    .then(function (selected) {
        for(var s of selected){
            var option = new Option(s.text, s.id, true, true);
            console.log(option)
            skillsSelect.append(option).trigger('change.select2');
        }
        skillsSelect.trigger({
            type: 'select2:select',
            params: {
                data: selected
            }
        });
    })
    .catch(function(err){
        console.log("$.getJSON('/api/skills/user/') failed " + err)
    })

    var dataBase=[];

    $.getJSON('/api/skills/all')
    .done(function(response) {
        console.log(".done response: " + JSON.stringify(response))
    })
    .fail(function(err){
        console.log("$.getJSON('/api/skills/all') failed " + err)
    })
    .then(function(alldata){

        $.each(alldata, function(i, skill){
            dataBase.push({id: skill._id, text: skill.skill})
        })

        console.log(".then dataBase: " + JSON.stringify(dataBase));


        $('.select2-container')
            .select2({

                data: dataBase,

                placeholder: 'Start typing to add skills...',
                width: 'style',
                multiple: true,

                createTag: function(tag) {
                    return {
                        id: tag.term,
                        text: tag.term.toLowerCase(),
                        isNew : true
                    };
                },

                tags: true,
                tokenSeparators: [',', '.']
            })
    })
});

Upon running

console.log(".then dataBase: " + JSON.stringify(dataBase));
, the following output is displayed:

.then dataBase: [
{"id":"5c9742d88aab960fa7ca3d22","text":"perl"},{"id":"5c9742e18aab960fa7ca3d23","text":"python"},{"id":"5c9744b9f042ad10ae6240b7","text":"drinking coffee"},{"id":"5c974be7fdae0712996657a4","text":"communication"},{"id":"5c974df73957e012afdd2591","text":"data analysis"},{"id":"5c979fcdbd5d082e0a...etc.
]

The stack trace of the error is as follows:

select2.full.js:4928 Uncaught TypeError: Cannot read property 'replace' of null
    at stripDiacritics (select2.full.js:4928)
    at matcher (select2.full.js:4964)
    at DecoratedClass.SelectAdapter.matches (select2.full.js:3411)
    at HTMLOptionElement.<anonymous> (select2.full.js:3271)
    at Function.each (jquery.js:354)
    at jQuery.fn.init.each (jquery.js:189)
    at DecoratedClass.SelectAdapter.query (select2.full.js:3262)
    at DecoratedClass.Tags.query (select2.full.js:3700)
    at DecoratedClass.<anonymous> (select2.full.js:598)
    at DecoratedClass.Tokenizer.query (select2.full.js:3803)

This error traces back to the function defined below:

function stripDiacritics (text) {
    // Utilized 'uni range + named function' from http://jsperf.com/diacritics/18
    function match(a) {
        return DIACRITICS[a] || a;
    }
    return text.replace(/[^\u0000-\u007E]/g, match);
}

The version of select2 being used is v4.0.6:

https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.1/js/select2.full.js

Answer №1

It appears that the issue may lie with the positioning of your jQuery code or a timeout causing you to receive an empty value:

$(document).ready(function() {
var dataBase = [
{"id":"5c9742d88aab960fa7ca3d22","text":"perl"},{"id":"5c9742e18aab960fa7ca3d23","text":"python"},{"id":"5c9744b9f042ad10ae6240b7","text":"drinking coffee"},{"id":"5c974be7fdae0712996657a4","text":"communication"},{"id":"5c974df73957e012afdd2591","text":"data analysis"},{"id":"5c979fcdbd5d082e0a5f6930","text":"reading"},{"id":"5c97bdd5500aa73961237dc9","text":"analysis"},{"id":"5c97bea16daa4639b441abe8","text":"writing"}
];
    $('.select2-container').select2(
{

                data: dataBase,

                placeholder: 'Start typing to add skills...',
                width: 'style',
                multiple: true,

                createTag: function(tag) {
                    return {
                        id: tag.term,
                        text: tag.term.toLowerCase(),
                        isNew : true
                    };
                },

                tags: true,
                tokenSeparators: [',', '.']
            }
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.1/js/select2.full.js"></script>

<select class="select2-container" style="width:200px;">

</select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating various arrays of data

I am currently facing an issue with creating separate datasets based on the month value. Despite my efforts, all month values are being combined into a single dataset in my code. Any assistance in dynamically generating different datasets would be greatly ...

What is the best way to use a button to hide specific divs upon clicking?

Is there a way to use a button onclick event to hide specific divs within a parent div? I've tried using .toggleClass('.AddCSSClassHere') but I'm not sure how to apply it to multiple divs. The jQuery snippet provided only allows me to h ...

Understanding the process of parsing an array in form-data in Node.js

https://i.stack.imgur.com/FPhX1.png I'm currently facing an issue while trying to read the image above in Node.js. I am using Express.js and have attempted to debug req.body, but it is returning an empty object {}. Even though I am using app.use(bod ...

Adding Roles Using Discord.js - A Simple Guide

I'm currently working on a Discord bot using Discord.js, and I am trying to implement a feature where users can use a command to assign themselves a role. However, despite my best efforts, I am unable to get this functionality to work. In my bot' ...

The printing feature in javascript does not include the ability to print values from textboxes

I'm encountering an issue when trying to print an HTML table with textboxes that should get their values from another function. However, the preview is not showing anything. Below is the complete code: <html> <head></head> < ...

Using Modal Functions in AngularJS Controller

I have been working on a project that utilizes the ui.bootstrap. As per the instructions from the tutorial I followed, my setup looks something like this: 'use strict'; angular.module('academiaUnitateApp') .controller('EntryCtr ...

Displaying [object Object] in Angular Material datatable

I am currently working on implementing a datatable component using Express and Firebase DB. Below is the service request data: getText() { return this.http.get<nomchamp[]>(this.url) .map(res => { console.log(res); return res }); ...

Encountering a problem with integrating Vue js and making a jquery

Hello there! I'm currently working on fetching data through ajax and utilizing a vue wrapper component. Here's the code snippet I'm using: <html> <head> <title>title</title> <meta charset="UT ...

What is the simplest method for fetching and parsing JSON data with jQuery and JavaScript?

I'm having trouble making this code snippet work. I can't seem to figure it out. The objective is to retrieve and parse a JSON object in the simplest and easiest way possible. Here's the code snippet. <!DOCTYPE html> <html> &l ...

Deleting the stylesheet exclusively within the confines of the React application window

Here is an image that will help illustrate the issue: https://i.stack.imgur.com/VA7fw.png If you want to check out the code sandbox for this problem, you can visit: https://codesandbox.io/s/annoying-stylesheet-2gpejc?file=/public/index.html I am current ...

testing exceptions with Jest: a step-by-step guide

As a beginner with Jest, I am currently working on a program to delve deeper into JavaScript. While my tests are functioning properly, I'm wondering if it would be better to replace the try/catch blocks with exceptions. I feel like there might be a mo ...

The hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...

Is it necessary to incorporate express in a Next.js project?

I'm currently working on a website using Next.js. With Next.js, I have access to features like SSR and dynamic routing. Is it necessary for me to incorporate express into my project? If yes, what are the reasons behind needing to use it? What unique ...

What causes unescaped HTML characters to become unescaped when using $('div :not(script)').contents().filter(function()?

Developing a Chrome Extension that utilizes a click-to-call API, I have encountered an issue where certain pages are displaying unusual behavior. After investigating, I have identified this specific code snippet as the source of the problem. var rxpCtc = n ...

Guidance on using an array to filter an object in Javascript

Looking at the object structure in Chrome Dev Tools, it appears like this: obj: { 1: {...}, 2: {...}, 3: {...}, 4: {...}, 5: {...}, } On the other hand, there is a simple array as well: arr: [1,3,5,7] The goal here is to filter the object bas ...

Navigating through child elements within a div using JavaScript

I recently coded a div using this snippet... let sidebarBox = document.createElement("div"); sidebarBox.id = "sidebarBox"; ...and then I created a second div like so... let sidebarAd = document.createElement("div"); sidebarAd.className = "sidebarAd"; B ...

Is there a way to incorporate the information from PHP files into the output produced by JavaScript?

I am currently working on a JavaScript script that scrapes data and displays the result on the screen successfully. However, I now face a challenge in wrapping this output with pre and post content from PHP files for formatting purposes. Here is an overvi ...

What is the best method for serving static files within a nested EJS view directory?

Assuming I have the directory structure below: |--Views/ | --partial/ | --links.ejs | |--assets/ | --css/ | --styles.css | |--server.js Code for links.ejs <link rel="stylesheet" type="text/css" href="css/forms/switches.css"& ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...