How to use select2 with Meteor?

时光毁灭记忆、已成空白 提交于 2020-01-03 13:02:49

问题


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.


回答1:


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?


来源:https://stackoverflow.com/questions/33422127/how-to-use-select2-with-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!