Select2: how to add a link instead of "No results found" text?
Asked Answered
S

3

2

Following is my code:

$('#cow_id_2').select2({
        allowClear: true,
        placeholder: "Search a cow/dam ID",
        formatNoMatches: function (term) {
            return "<a href=/'http://google.com/'>Add</a>";
        }
    });

When I try to add a link the plugin just stop working. I am using Select2 4.0.3 version

Sitra answered 13/6, 2016 at 19:22 Comment(0)
M
19

If you're using version 4 or newer of select2, try this:

$('#cow_id_2').select2({
        allowClear: true,
        escapeMarkup: function (markup) { return markup; },
        placeholder: "Search a cow/dam ID",
        language: {
            noResults: function () {
                 return "<a href=/'http://google.com/'>Add</a>";
            }
        }
    });
Mortise answered 17/6, 2016 at 13:19 Comment(0)
D
5

The selected answer is correct. Here is a little precision. Instead of overriding escapeMarkup, you can return a jQuery object in the noResults method. Like this :

$('#cow_id_2').select2({
    allowClear: true,
    placeholder: "Search a cow/dam ID",
    language: {
        noResults: function () {
            return $("<a href='http://google.com/'>Add</a>");
        }
    }
});
Dupre answered 9/12, 2019 at 10:16 Comment(1)
What if I want to set a language too. If I use language property the way mentioned here, I can get custom no result element but select2 doesn't take into consideration the current user language which I was previously passing in language property as language: "fr". I need to be able to add a button if no result but also leave translation for other text as such as 'please enter 2 or more characters'.Commoner
A
0

If anyone wants to achieve this while also using the search term, you can 'cheat' using this:

$('#cow_id_2').select2({
    allowClear: true,
    escapeMarkup: function (markup) { return markup; },
    placeholder: "Search a cow/dam ID",
    language: {
        noResults: function () {
            var term = $('#cow_id_2').data("select2").selection.$search.val();
            return `Couldn't find ${term}`;
        }
    }
});
Athwartships answered 16/11, 2023 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.