Getting the text cursor to show up at the end of a string in a text field (such as input text or textarea) is useful when you want to allow typing to begin at the end of the text. See the demo (works with Internet Explorer and Firefox) and then the source code below:
Source Code:
<script language="javascript">
<!--
function txtJumpToEnd(targetTxtFieldId) {
var targetTxtFieldContent = document.getElementById(targetTxtFieldId).value;
var oRange; var iStart = 0, iEnd = 0;
iEnd = targetTxtFieldContent.length;
if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) {
oRange = document.getElementById(targetTxtFieldId).createTextRange();
oRange.moveStart("character", iEnd); oRange.moveEnd("character", iEnd);
oRange.select();
}
else {
oRange = document.getElementById(targetTxtFieldId).setSelectionRange(iEnd, iEnd);
}
document.getElementById(targetTxtFieldId).focus();
}
//-->
</script>
HTML Code:
<input type="text" name="test" id="test" size="60" value="Cursor placed at end of this text when button is clicked" />
<input type="button" name="btn" id="btn" value="Place Cursor At End Of Text" onmouseup="txtJumpToEnd('test');" />