How to set cursor focus to the end of text in textbox using Javascript

This example will be helpful to set the cursor focus to the end of the string in the textbox. Also can reuse the function to set the focus to first character of the textbox.

<!DOCTYPE html>
<html>
  <head>
    <title>Javascript example</title>
    <script type="text/javascript">
      function focusToText(end_or_start){
        var input = document.getElementById('username')
        if(end_or_start == 'end'){
          input.setSelectionRange(input.value.length, input.value.length);
        }else if(end_or_start == 'start'){
          input.setSelectionRange(0, 0);
        }

        input.focus();

      }
    </script>
  </head>
  <body>
    <input type="text" name="username" id="username"><br/><br/>
    <button onclick="focusToText('start')">Focus to start</button>
    <button onclick="focusToText('end')">Focus to end</button>
  </body>
</html>

Happy coding!

Updated: June 17, 2020 — 12:23 pm

1 Comment

Add a Comment
  1. Having read this I believed it was really informative. I appreciate you finding the time and energy to put this content together. I once again find myself spending a significant amount of time both reading and leaving comments. But so what, it was still worthwhile! Fidela Emmet Ham

Leave a Reply