Steven
Steven

Reputation: 167

jQuery focus() to set focus in the end of the input

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>

Upvotes: 0

Views: 430

Answers (2)

smwhr
smwhr

Reputation: 683

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)

Upvotes: 0

treatycity
treatycity

Reputation: 141

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

Upvotes: 3

Related Questions