0

I'm using jQuery focus to set focus on a newly created input.

It works well, but the focus is set in the beginning of the input even though there is a pre-defined text. How can I place it after the text?

$('.button').on('click', function () {
$('.container').html('<input type="text" class="newinput" value="word">');
$('.newinput').focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="button">create and focus</button>
<br />
<div class="container"></div>
Steven
  • 167
  • 8

2 Answers2

2

A simple trick would be to set focus and then set the value, if your scenario allows for that.

$('.button').on('click', function() {
  $('.container').html('<input type="text" class="newinput" value="">');
  $('.newinput').focus();
  $('.newinput').val("word");
})

Working fiddle: https://jsfiddle.net/tqomec7d/

If that doesn't work for you, I think one of the answers here might help: Use JavaScript to place cursor at end of text in text input element

treatycity
  • 133
  • 1
  • 6
0

Use setSelectionRange (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange)

First, compute the length of the value in the input, then setSelectionRange(length+1, length+1)

kmoser
  • 8,780
  • 3
  • 24
  • 40
smwhr
  • 675
  • 6
  • 22