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

Retrieve key codes from inputs sharing the same class

My webpage contains multiple text inputs that all share the same class for various reasons. Currently, I am attempting to capture the ESC button press when an input is focused and alert whether the input has a value or not. However, this functionality on ...

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...

Tips for displaying or concealing table rows with form fields on a php site by utilizing jquery/ajax and a drop-down menu selection

Is there a way to hide or unhide table rows with form fields in a php website based on a dropdown selection using jquery/ajax? The current script I have only hides the field, leaving blank rows. How can I also hide the respective table rows? Thank you for ...

`Is there a way to avoid extra re-renders caused by parameters in NextJS?`

I am currently in the process of implementing a standard loading strategy for NextJS applications using framer-motion. function MyApp({ Component, pageProps, router }) { const [isFirstMount, setIsFirstMount] = useState(true); useEffect(() => { ...

What is the best way to find a specific string within an array of strings?

I have a list of tasks as strings: todo=[ 'Get up', 'Brush my teeth', 'Go to work', 'Play games' ]; I am attempting to compare it with this: Template: <input (input)="checkArrays($event)" /> In my ...

Sending emails with SMTP in JavaScript using the mailto form

I'm facing a challenge with my form. I am looking for a way to have the Send-email button trigger mailto without opening an email client, instead automatically sending via JavaScript (smtp). I'm not sure if this is achievable or if I'm askin ...

Mongoose: When encountering a duplicate key error (E11000), consider altering the type of return message for better error handling

When trying to insert a duplicate key in the collection, an error message similar to E11000 duplicate key error collection ... is returned. If one of the attributes is set as unique: true, it is possible to customize this error message like so: {error: ...

Obtaining the NodeValue from an input of type <td>

I have a HTML code snippet that I am trying to parse in order to extract the nodeValue of all elements within the table columns. <table id="custinfo"> <tr> <td><label>First Name</label></td> <td& ...

Using AngularJs to have two ui-views on a single page

As a beginner in AngularJs, I encountered an issue with having two ui-views on the same page. When I click a button to show the view for goals, both the form for goals appear in ui-view 1 and ui-view 2 simultaneously. I have been working with states but I ...

Is it possible to retrieve a physical address using PHP or Javascript?

Is it possible to retrieve the physical address (Mac Address) using php or javascript? I need to be able to distinguish each system on my website as either being on the same network or different. Thank you ...

How to invoke a function from a different ng-app in AngularJS

I have 2 ng-app block on the same page. One is for listing items and the other one is for inserting them. I am trying to call the listing function after I finish inserting, but so far I haven't been successful in doing so. I have researched how to cal ...

Is it possible to incorporate swigjs within scripts?

Currently, I am stuck while working on my website using a combination of nodejs, express, and swigjs. The issue I am facing involves a <select> element that is populated by options from a variable passed to my template. When a user selects an option, ...

Updating a .txt file using JavaScript

Is there a method on the client side to add text to a file called text.txt using JavaScript? In Python: f = open("text.txt","w") f.write("Hello World") f.close() The code snippet above would input "Hello World" into the text file. I am looking for a sim ...

Having trouble configuring Travis; crashes just before installation begins

Today I attempted to set up Travis on my GitHub project but encountered a few roadblocks (refer to the screenshot). I experimented with different configurations in .travis.yml, such as the one below: language: node_js node_js: - "8.11.2" sudo: false b ...

Using PHP, Ajax, and JavaScript, display interactive data from the server in a dynamic modal popup listbox within a Tinymce-WordPress

Currently, I am in the process of developing a WordPress plugin using TinyMCE. The main functionality involves a button that triggers a popup modal with some list boxes. These list boxes need to be populated with values fetched from the server. To accompli ...

Verify the visibility of the toggle, and eliminate the class if it is hidden

I have implemented two toggles in the code snippet below. I am trying to find a solution to determine if either search-open or nav-open are hidden, and if they are, then remove the no-scroll class from the body element. $(document).ready(function() { ...

`Issues with CSS/JQuery menu functionality experienced in Firefox`

After creating a toggleable overlay menu and testing it in various browsers, including Internet Explorer, everything seemed to work fine except for one major issue in Firefox (version 46). The problem arises when toggling the overlay using the "MENU" butt ...

Enhancing leaflet popup functionality by incorporating ng-click into the onEachFeature function

After creating a map and connecting it with my geojson api, I encountered an issue when trying to link each marker popup with ng-click. Simply adding HTML like this did not work as expected: layer.bindPopup("<button ng-click='()'>+feature. ...

Looking to resolve a module-specific error in Angular that has not been identified

While practicing Angular, I encountered an error during compilation: Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app' i 「wdm」: Failed to compile. This is my app.compo ...

Render a select field multiple instances in React

I have 5 different labels that need to be displayed, each with a select field containing the options: string, fixed, guid, disabled Below is the code I've written: class CampaignCodeRenderer extends Component { state = { defaultCampaigns: ...