What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element
Simple. When editing or changing values, first put the focus then set value.
$("#catg_name").focus();
$("#catg_name").val(catg_name);
Try the following code:
$('input').focus(function () {
$(this).val($(this).val());
}).focus()
var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);
I've tried the following with quite great success in chrome
$("input.focus").focus(function () {
var val = this.value,
$this = $(this);
$this.val("");
setTimeout(function () {
$this.val(val);
}, 1);
});
Quick rundown:
It takes every input field with the class focus on it, then stores the old value of the input field in a variable, afterwards it applies the empty string to the input field.
Then it waits 1 milisecond and puts in the old value again.
Here’s a jsFiddle demo of my answer. The demo uses CoffeeScript, but you can convert it to plain JavaScript if you need to.
The important part, in JavaScript:
var endIndex = textField.value.length;
if (textField.setSelectionRange) {
textField.setSelectionRange(endIndex, endIndex);
}
I’m posting this answer because I already wrote it for someone else who had the same question. This answer doesn’t cover as many edge cases as the top answers here, but it works for me, and has a jsFiddle demo you can play with.
Here is the code from the jsFiddle, so this answer is preserved even if the jsFiddle disappears:
moveCursorToEnd = (textField) ->
endIndex = textField.value.length
if textField.setSelectionRange
textField.setSelectionRange(endIndex, endIndex)
jQuery ->
$('.that-field').on 'click', ->
moveCursorToEnd(this)
<div class="field">
<label for="pressure">Blood pressure</label>:
<input class="that-field" type="text" name="pressure" id="pressure" value="24">
</div>
<p>
Try clicking in the text field. The cursor will always jump to the end.
</p>
body {
margin: 1em;
}
.field {
margin-bottom: 1em;
}
Try this one works with Vanilla JavaScript.
<input type="text" id="yourId" onfocus=" let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">
In Js
document.getElementById("yourId").focus()