0

Hello I'm using tokenfield to create input tags.

I've tried to clone the element without success. Is there any way to do a proper cloning? This is for a dynamic form.

Problem : Fields doesn't work after the cloning. I think the issue is in to tokens.

This is my JavaScript code :

$('.tokenfield').tokenfield();

This is my cloning function :

$('.clone').on('click',function(){
  var newLine = $(".attribute:first").clone();
  $("#variants").append(newLine);
});

This is my HTML code :

<div id="variants">
  <div class="row attribute">
    <div class="col-lg-4">
      <div class="input-group"> <span class="input-group-prepend">
        <button class="btn btn-light clone" type="button"><i class="icon-plus3"></i></button>
        </span> <input type="text" class="form-control" placeholder="Left button"> </div>
      </div>
      <div class="col-lg-8">
        <div class="form-group mb-1"> <input type="text" class="form-control tags tokenfield" name="variant[value][]" value=""><br>
      </div>
    </div>
  </div>
</div>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Amine Bouhaddi
  • 554
  • 1
  • 7
  • 24
  • Use `.clone(true)` so it copies all the dynamic properties and event handlers. – Barmar Jun 22 '19 at 00:22
  • You're calling `.clone()` with no arguments you need `.clone(true)` to clone the events – chiliNUT Jun 22 '19 at 00:22
  • Thanks guys, i'm not talking about cloning function, i can clone but the tags doesn't works after the cloning ( i think i must generate a new token for tokenfield ) i have already tried, can you double check with me please, i need your help – Amine Bouhaddi Jun 22 '19 at 00:27
  • "I can clone but the tag doesnt work after cloning" if the tag doesnt work, then I would argue that no, you have not really cloned it. Passing `true` to `clone(` may solve your problem. – chiliNUT Jun 22 '19 at 01:15
  • the clone is ok, but the problem in tags inputs they doesn't works – Amine Bouhaddi Jun 22 '19 at 01:17

1 Answers1

0

You are cloning the whole .attribute div... Which includes an input that is has an instance of tokenkenfield on...

As Barmar said .clone(true) will "deep clone", meaning it will also clone the properties and events... But You are talking about an instance of a plugin on a child. That is where the story ends bad ;)

Happilly, there is a way. You simply have to create another instance of tokenkenfield on that new input.

Something like this:

$('.clone').on('click',function(){
  var newLine = $(".attribute:first").clone();
  $("#variants").append(newLine);
  $("#variants").find(".tokenfield").last().tokenfield();  // New instance here.
});

Disclaimer: Untested (But, hoppefully, you got the concept... ;) )

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64