SOLVED
http://jsfiddle.net/ArtofLife/u9d9d/
I have multiple TEXTAREA and BUTTON out side.. For inserting string in textarea, I used jQuery plugin (insertAtCaret). How to fill ONLY the last clicked TEXTAREA with text…?
<textarea name="answer_text[0]" cols="50" rows="3" style="width: 99%;">
AAA
</textarea>
<textarea name="answer_text[1]" cols="50" rows="3" style="width: 99%;">
BBB
</textarea>
<textarea name="answer_text[2]" cols="50" rows="3" style="width: 99%;">
CCC
</textarea>
<textarea name="answer_text[3]" cols="50" rows="3" style="width: 99%;">
Here should be:
<button class=insert name=insert>Insert</button>
</textarea>
<button class=insert name=insert>Insert</button>
<script type="text/javascript">
jQuery.fn.extend({
insertAtCaret: function(myValue) {
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
}
});
var pos = 0;
$('textarea').click(function() {
//Get the name of this clicked item
var pos = $(this).attr("name");
$('.insert').click(function() {
$('textarea[name^="' + pos + '"]').insertAtCaret('Actual button code');
});
return false;
});
</script>
Now I getting filed all the textareas that I clicked… http://jsfiddle.net/ArtofLife/u9d9d/15/
I want to be filled only the last textarea that is clicked, and not bubbling the variable pos..
It is because you have the
.insert‘sclickhandler inside thetextareaclickhandler. Whenever you click ontextareaa new handler is attached and it keeps attaching as and when u click on anytextarea. Move it outside it will work fine.Demo