Reputation: 88197
If I have more than 1 instance of the same plugin on the same page how can I separate functionality. eg. in this demo http://jsfiddle.net/3jwAK/, I have a plugin "editor
" that appends a link simulating some plugin/widget button, that when clicked will append a line to the textarea
.
The problem with it currently is it only targets the last textarea
Code looks like
JS
(function($) {
$.fn.editor = function(options) {
var helpers = {
rand: function() {
return Math.round(Math.random() * 20);
}
};
return this.each(function() {
$this = $(this);
var div = $("<a>", {
text: "Add Random Number",
href: "#",
click: function() {
$this.val( $this.val() + "\n" + helpers.rand() );
}
});
$this.before(div);
});
}
})(jQuery);
HTML
<textarea name="txtArea1" cols="50" rows="6" id="editor1"></textarea>
Upvotes: 1
Views: 2285
Reputation: 20602
The problem is the variable $this
needs to be a local copy in each run of that function. Put var
in front of it.
var $this = $(this);
Updated: http://jsfiddle.net/3jwAK/1/
Upvotes: 4