| ||||
A blog about Ruby, Rails and other Tech. Mostly.Back to blog
I needed to control the cursor in a textarea from javascript. This is how to do it. Note this is only for Mozilla - some mods will be required for IE. (My application only uses Mozilla.) With this code you can insert text, move the cursor left and right and delete characters.
<script>
function addText( input, insText, pos, del ) {
input.focus();
var len = input.selectionEnd;
input.value = input.value.substr( 0, len-del )
+ insText + input.value.substr( len );
input.setSelectionRange(len+insText.length+pos-del,len+insText.length+pos-del);
}
</script>
<form onsubmit="return false;">
<textarea></textarea>
<input type="button" onclick="addText(this.form.elements[0],'', -1, 0);"
value="Left">
<input type="button" onclick="addText(this.form.elements[0],'', 1, 0);"
value="Right">
<input type="button" onclick="addText(this.form.elements[0],'X', 0, 0);"
value="X">
<input type="button" onclick="addText(this.form.elements[0],'', 0, 1);"
value="Del">
</form>
Back to blog |