[Javascript] Setting cursor position to the end of text field

May 9, 2008 · Filed Under JavaScript · Comment 

Usually javascript to set cursor position to the end of a text field? I bet lots of people looking for workaround on this. The trick is actually simple but yet so many people never though of it. So to get this done, just do set the text vield value before you focus on the text field, here some example code:

let say you want to set a value in the a text field after the page just finish loaded and make the cursor start at the end of that text field.

Code:

<!– in the HEAD –>
<script language=”JavaScripts”>
function setTextField(){
document.myForm.myTextFieldName.value = “My name is “;
document.myForm.myTextFieldName.focus();
}
</script>

<!– in the BODY TAG–>

<body onLoad=”setTextField()”>

<!– in the FORM –>

<form name=”myForm”>
<input type=”text” name=”myTextFieldName” value=””>
</form>

Thats all you need!