ARTICLE

While scrolling to the caret position of an html input

The html input of type β€œtext” can be focused at any position of the text inside it.

When the focus is set to the input and selection range is set through javascirpt, it doesn’t work as expected.

<script type="text/javascript">
function select_at_j() {
  document.getElementById('testid').focus();
  document.getElementById('testid').setSelectionRange(10, 10);
}
</script>
<input style="width:50px" id="testid" value="abcdefghijklmnopqrstuvwxyz">
<button onclick="select_at_j()">select 10,10</button>

If we check this out, the 10th alphabet is focused on second click only.

But there is a work around which is too easy. Just swap the two lines of code as,

<script type="text/javascript">
function select_at_j() {
       document.getElementById('testid').setSelectionRange(10, 10);
    document.getElementById('testid').focus();
}
</script>
<input style="width:50px" id="testid" value="abcdefghijklmnopqrstuvwxyz">
<button onclick="select_at_j()">select 10,10</button>

Warm regards

NEWSLETTER

Subscribe to the Algolassi newsletter

Get practical .NET, C#, Blazor, SQL Server and developer tips in your inbox. No spam, just useful updates.

πŸ€– AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

πŸ’¬ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.