I have a textbox with some words and text.The thing I want to do is this that when the user clicks on a button add some words to the text of the textbox from the current position of the pointer.How to do this? This is the textbox and the button:
<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" id="btn" value="OK" />
Maybe a shorter version, http://jsfiddle.net/NaHTw/4/ would be easier to understand?
jQuery("#btn").on('click', function() {
var caretPos = document.getElementById("txt").selectionStart;
var textAreaTxt = jQuery("#txt").val();
var txtToAdd = "stuff";
jQuery("#txt").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
});
Quite coincident, I just answer a similar question a few minutes ago. You can use a custom function like this:
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();
}
})
}
});
Basically, this plugin allows you to insert a piece of text at caret of multiple textbox
or textarea
. You can use it like this:
$('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');
Working Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With