Here is my HTML
<div class="suggestion-box col-sm-12">
<div class="col-sm-1 parantheses">(</div>
<div class="col-sm-1 parantheses">)</div>
</div>
<br>
<textarea class="entry-box col-sm-12" type="text">temp<20 && hum<10</textarea>
When clicked on any of the "parantheses" classes, "(" or ")" should get inserted at the cursor position in the textarea.
How can this be achieved in jquery? Looked through few posts where a custom text can be inserted at the beginning/end only. But my requirement is different.
Any help would be much appreciated. Thank you!
Edit: (This DID NOT work)
I have posted the right answer based on Pankaj's reference link.
function getCaret(el) {
if (el.prop("selectionStart")) {
return el.prop("selectionStart");
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
function appendAtCaret($target, caret, $value) {
var value = $target.val();
if (caret != value.length) {
var startPos = $target.prop("selectionStart");
var scrollTop = $target.scrollTop;
$target.val(value.substring(0, caret) + ' ' + $value + ' ' + value.substring(caret, value.length));
$target.prop("selectionStart", startPos + $value.length);
$target.prop("selectionEnd", startPos + $value.length);
$target.scrollTop = scrollTop;
} else if (caret == 0) {
$target.val($value + ' ' + value);
} else {
$target.val(value + ' ' + $value);
}
};
$('textarea').each(function() {
var $this = $(this);
$this.click(function() {
//get caret position
var caret = getCaret($this);
//append some text
appendAtCaret($this, caret, 'Some text');
});
});