Daniel Bernhard
Daniel Bernhard

Reputation: 382

Dynamically add Select2 fields to form

I'm using Select2 with Meteor and Handlebars and am trying to add Select2 <input type="hidden"fields dynamically, for use with Select2. The hidden fields are showing up, but Select2 register them.

The HTML looks like this.

{{#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}}

Event handler looks like this:

'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>');  
}

The select2 is added when the page is created:

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

Any help would be very much appreciated!!

Upvotes: 3

Views: 5336

Answers (1)

John S
John S

Reputation: 21492

It sounds like you are instrumenting your Select2 elements at page load, but that will instrument only those that exist at that time. You need to instrument the ones you dynamically add as you add them.

You could try this:

'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: [",", " "] });
}

Upvotes: 7

Related Questions