KANAYO AUSTIN KANE KANAYO AUSTIN KANE - 4 months ago 20
Javascript Question

Setting the cursor between two quotes

I have this textarea that when I click a link, 2 double quote marks are been inserted:

<textarea name="comment" id="comment" placeholder="Comment..."></textarea>
<div id="insert">
<a href="javascript:;" title='""'>QUOTES</a>
</div>
<script type="text/javascript" src="jscript.js"></script>
<script type="text/javascript">
$('#insert a').click(function () {
var smiley = $(this).attr('title');
ins2pos(smiley, 'comment');
});

function ins2pos(str, id) {
var TextArea = document.getElementById(id);
var val = TextArea.value;
var before = val.substring(0, TextArea.selectionStart);
var after = val.substring(TextArea.selectionEnd, val.length);

TextArea.value = before + str + after;
setCursor(TextArea, before.length + str.length);

}

function setCursor(elem, pos) {
if (elem.setSelectionRange) {
elem.focus();
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
var posr = pos - 1;
range.moveEnd('character', posr);
range.moveStart('character', posr);
range.select();
}
}
</script>


When the QUOTE link is been clicked the cursor goes after the last character in the textarea like this
""|
but I want the cursor to be in between the 2 quote marks something like this
"|"

Answer

This is the solution

setCursor(TextArea, before.length + str.length - 1);