动态添加Select2字段以形成

Dan*_*ard 2 jquery meteor jquery-select2

我正在使用带有Meteor和Handlebars的Select2,我正在尝试<input type="hidden"动态添加Select2 字段,以便与Select2一起使用.隐藏字段显示,但Select2注册它们.

HTML看起来像这样.

{{#each update.ingredients}}
  <div class="ingredient">
     <input class="quant span2" type="text" placeholder="Quantity" value="{{quantity}}"/>
     <input class="unit span1" type="hidden" placeholder="Unit" value="{{unit}}"/>
     <input class="ing" type="hidden" placeholder="Ingredient" value="{{ingredient}}"/>
  </div>
{{/each}}
Run Code Online (Sandbox Code Playgroud)

事件处理程序如下所示:

'click .addIngredient': function () {
  $("#input_ingredients").append('<div class="ingredient"><input class="quant span2" type="text" placeholder="Quantity"/><input class="unit span1" type="hidden" placeholder="Unit"/><input class="ing" type="hidden" placeholder="Ingredient"/></div><br>');  
}
Run Code Online (Sandbox Code Playgroud)

创建页面时添加select2:

'click .add': function () {
  $(".tags").select2({
    tags: checkTags(),
    tokenSeparators: [",", " "]
  });
  $(".ing").select2({
    tags: checkIngredients(),
    tokenSeparators: [",", " "]
  });
  $(".unit").select2({
    tags: checkUnits(),
    tokenSeparators: [","]
  });
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感谢!!

Joh*_*n S 7

听起来你在页面加载时正在检测你的Select2元素,但这只会检测那时存在的那些元素.您需要检测添加它们时动态添加的那些.

你可以试试这个:

'click .addIngredient': function () {
    var $div = $('<div class="ingredient"><input class="quant span2" type="text" placeholder="Quantity"/><input class="unit span1" type="hidden" placeholder="Unit"/><input class="ing" type="hidden" placeholder="Ingredient"/></div>');
    $("#input_ingredients").append($div).append('<br />');  
    $div.find('.tags, .ing, .unit').select2({ tags: checkTags(), tokenSeparators: [",", " "] });
}
Run Code Online (Sandbox Code Playgroud)