How to change formatNoMatches in Lect2 4.0.0?

Asked

Viewed 1,140 times

1

I’m using the Lect2 4.0.0 and I am having trouble changing the way the message is shown which indicates not having found results. In the old version used formatNoMatches to change the presentation, how is it done now? BS: I cannot change this directly in the file en.BR.js because every select has a different behavior.

$('#id_categoria').select2(
    {
        placeholder:'Selecione',
        minimumInputLength: 2, 
        formatNoMatches: function(term) {
            return "Nenhum resultado. Adicionar " + term + "?";
        }
    }
);

1 answer

1


It seems that the standard way to do this in version 4 is by language file.

However I did a little bit and I ended up developing a work-Around that works:

$(function() {
  var id_categoria = $('#id_categoria')
    .select2({
      placeholder: 'Selecione',
      minimumInputLength: 2,
      language: $.extend({},
        $.fn.select2.defaults.defaults.language, {
          noResults: function() {
            var term = id_categoria
              .data('select2')
              .$dropdown.find("input[type='search']")
              .val();

            return $("<span>Nenhum resultado. <span class='add'>Adicionar <b>" + term + "</b></span>?</span>");
          }
        })
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/js/select2.min.js"></script>

<select class="js-example-responsive" id="id_categoria" style="width: 50%">
</select>

I know it’s not very pretty, but it’s the only way I could define the text, dynamically for select.

  • This really works, however it is not returning HTML code, know how to solve it? The idea would be to return one return "Nenhum resultado. <span class='add'>Adicionar <b>" + term + "</b></span>?";

  • 1

    I edited the answer to return HTML... just return a jQuery object: $("<span>what ever</span>")

  • @Orion your idea is to return the "term" to later send it in post to save right ?

  • @Exact rod, by clicking add I will catch the term and save via Ajax, and add to select.

  • @Orion and where will you leave the button to send the post? rs (I’m also in need of something like kk)

  • @Miguelangelo I opened a question in the Lect2 repository to see if there is a simpler solution for this, I had searched but found nothing in the documentation. It was right to have an option to do this by default.

  • @Rod by clicking on span I’ll pick up the typed text and add to the select.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.