JavaScript - How to Place Cursor at End of Text in Text Input Field?
Last Updated :
26 Nov, 2024
Improve
Here are the various methods to place cursor at the end of text in text input field in JavaScript
Using HTMLInputElement.setSelectionRange() Method
The setSelectionRange() method is the most basic way to move the cursor within a text input or textarea. It allows you to set the start and end positions of the current text selection. To place the cursor at the end, you can set both the start and end positions to the length of the text.
<!DOCTYPE html>
<html>
<head>
<title>Place Cursor at End of Text Input</title>
</head>
<body>
<input type="text" id="myInput" value="Hello, world!" />
<button onclick="moveCursorToEnd()">Place Cursor at End</button>
</body>
<script>
function moveCursorToEnd() {
const input = document.getElementById('myInput');
const length = input.value.length;
// Focus on the input
input.focus();
// Set the cursor to the end
input.setSelectionRange(length, length);
}
</script>
</html>
Output
