capiono
capiono

Reputation: 2997

Dynamic elements not created properly in Jquery Plugin

I wrote a masking jquery that is suppose to add dynamic elements the an existing input element.

var link = $('<a title="show" role="link" href="#" class="masker-value">show</a>');

wrapper: function() {
  container = $(container)
    .attr('ispartial', this.options.partial)
    .attr('readyonly', this.options.readyOnly);
  $(this.element).wrap(container);
  if (!this.options.hideToggle)
    $(this.element).after(link);
} 

If I have a single input on a page, the code above works fine, but if I have multiple input, the link is only added to the last input.

Demo

Upvotes: 1

Views: 46

Answers (1)

Huso
Huso

Reputation: 1486

Add the following line to the wrapper function:

link = $('<a title="show" role="link" href="#" class="masker-value">show</a>');

You defined link globally outside the wrapper function so its always refering to the same object, which gets moved in the DOM.

Example: https://jsfiddle.net/nxvdm5hr/5/

Further explanation:

When you use $('<a/>'), jQuery creates an input DOM element.

When you .after() that element, it detaches from the previous position.

You could also modify the var link to just HTML code, which will also fix your problem.

Upvotes: 1

Related Questions