admin管理员组

文章数量:1316023

I am using select2 in a node express app, and when I supply an array as data source data: dataBase I get the error Uncaught TypeError: Cannot read property 'replace' of null.

I have tried using an ajax source as data, which works but the data are not filtered on typing (this is mented out below) - it appears that matching only works with array data:

matcher only works with locally supplied data (e.g., via an array! When a remote data set is used, Select2 expects that the returned results have already been filtered on the server side.

I am now building an array from the ajax GET call: $.getJSON('/api/skills/all'), and then providing this as the datasource in my select2 call:

$(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: [',', '.']
            })
    })
});

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

.then dataBase: [
{"id":"5c9742d88aab960fa7ca3d22","text":"perl"},{"id":"5c9742e18aab960fa7ca3d23","text":"python"},{"id":"5c9744b9f042ad10ae6240b7","text":"drinking coffee"},{"id":"5c974be7fdae0712996657a4","text":"munication"},{"id":"5c974df73957e012afdd2591","text":"data analysis"},{"id":"5c979fcdbd5d082e0a5f6930","text":"reading"},{"id":"5c97bdd5500aa73961237dc9","text":"analysis"},{"id":"5c97bea16daa4639b441abe8","text":"writing"}
]

Here is the stack trace of the error:

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)

Which is this function:

function stripDiacritics (text) {
    // Used 'uni range + named function' from 
    function match(a) {
        return DIACRITICS[a] || a;
    }
    return text.replace(/[^\u0000-\u007E]/g, match);
}

I'm using select2 v4.0.6:

.0.6-rc.1/js/select2.full.js

I am using select2 in a node express app, and when I supply an array as data source data: dataBase I get the error Uncaught TypeError: Cannot read property 'replace' of null.

I have tried using an ajax source as data, which works but the data are not filtered on typing (this is mented out below) - it appears that matching only works with array data:

matcher only works with locally supplied data (e.g., via an array! When a remote data set is used, Select2 expects that the returned results have already been filtered on the server side.

I am now building an array from the ajax GET call: $.getJSON('/api/skills/all'), and then providing this as the datasource in my select2 call:

$(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: [',', '.']
            })
    })
});

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

.then dataBase: [
{"id":"5c9742d88aab960fa7ca3d22","text":"perl"},{"id":"5c9742e18aab960fa7ca3d23","text":"python"},{"id":"5c9744b9f042ad10ae6240b7","text":"drinking coffee"},{"id":"5c974be7fdae0712996657a4","text":"munication"},{"id":"5c974df73957e012afdd2591","text":"data analysis"},{"id":"5c979fcdbd5d082e0a5f6930","text":"reading"},{"id":"5c97bdd5500aa73961237dc9","text":"analysis"},{"id":"5c97bea16daa4639b441abe8","text":"writing"}
]

Here is the stack trace of the error:

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)

Which is this function:

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

I'm using select2 v4.0.6:

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

Share Improve this question edited Mar 25, 2019 at 12:42 fugu asked Mar 25, 2019 at 11:54 fugufugu 6,5789 gold badges42 silver badges79 bronze badges 10
  • .replace doesn't occur anywhere in your code sample. Can you use the stack trace to show where the error is originating from? – James Monger Commented Mar 25, 2019 at 11:56
  • @JamesMonger I've added it to the question – fugu Commented Mar 25, 2019 at 11:59
  • Which version of select2 is used? – raina77ow Commented Mar 25, 2019 at 12:00
  • @raina77ow - v4.0.6 - I've updated the question to include this – fugu Commented Mar 25, 2019 at 12:02
  • 1 I made a test here from what you inform but there is no problem – HudsonPH Commented Mar 25, 2019 at 12:43
 |  Show 5 more ments

1 Answer 1

Reset to default 6

There is no problem on part that you inform, maybe is the position of you jquery or timeout and you are getting empty value:

$(document).ready(function() {
var dataBase = [
{"id":"5c9742d88aab960fa7ca3d22","text":"perl"},{"id":"5c9742e18aab960fa7ca3d23","text":"python"},{"id":"5c9744b9f042ad10ae6240b7","text":"drinking coffee"},{"id":"5c974be7fdae0712996657a4","text":"munication"},{"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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare./ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare./ajax/libs/select2/4.0.6-rc.1/js/select2.full.js"></script>

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

</select>

本文标签: javascriptUncaught TypeError Cannot read property 39replace39 of null in select2Stack Overflow