Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use select2 with Meteor?

can someone explain to me how select2 works with Meteor? I am using zimme:select2-boostrap3-css and I have no clue on how to use it.

I checked both the original select2 github page and the one from the package. The first one explains how to use it without Meteor.

Do I just add the jQuery code to one of my *.js-files in order to get it to work?

In HTML:

<select class="input" id="clientName" name="clientName">
    {{#each getClients}}
        <option value="{{clientName}}" data-id={{_id}}>{{clientName}}</option>
    {{/each}}
</select>

In JS:

$("#clientName").select2();

Because this doesn't work.

When loading my page I get this error Uncaught TypeError: $(...).select2 is not a function.

like image 728
Moritz Schmitz v. Hülst Avatar asked Oct 18 '22 23:10

Moritz Schmitz v. Hülst


1 Answers

Uncaught TypeError: $(...).select2 is not a function

The error above happening because you haven't included the JavaScript for Select2, as identified in the comments. The atmosphere package you linked to is just for providing Bootstrap-esque styling on top of the existing Select2 package.

You should also include meteor add natestrauser:select2

The next problem you may run into is that when the JavaScript runs, <select class="input" > might not be loaded into the DOM so $("#clientName") won't find anything. To wait to initialize Select2 until the page is loaded, you should wrap the code in the jQuery's DOM ready function $(function(){}); and wrap that in the Meteor.Startup() for good measure like this:

Meteor.startup(function () {
  $(function(){
    $("#clientName").select2();
  });
});

Working Demo in Meteorpad

Further Reading:

  • How to run JQuery code when document is ready in Meteor?
like image 135
KyleMit Avatar answered Nov 01 '22 17:11

KyleMit