JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Complete :: CROSS-BROWSER End-of-Textbox solution</h2>
<br />
<a href="#">CLICK THIS TO GO TO THE END</a><br/><br />
<input id="test" value="This is a test string" />
<br />
<div id="result"></div>
CSS
body { padding:20px; color:#242424; font-family: "Lucida Grande", Tahoma, "Trebuchet MS"; }
h2 { background:#5279a4; color:#fff; padding:5px; }
div { padding:5px; }
JavaScript
$("a").click(function(e){
e.preventDefault();
var input = $("#test");
// since we are setting it to the END we need the .length
var len = input.val().length;
input.val(input.val());
// ^ this is used to not only get "focus", but
// to make sure we don't have it everything -selected-
// (it causes an issue in chrome, and having it doesn't hurt any other browser)
var status = setCaretPosition('test', len);
// Just to show whether it worked or not
// Obviously don't have to use the boolean return it brings back
$('#result').text(status ? 'Oh snap dawg, it worked!' : 'Fail city bitch');
});
function setCaretPosition(elemId, caretPos) {
var el = document.getElementById(elemId);
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
}
else {
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
}
else { // fail city, fortunately this never happens (as far as I've tested) :)
el.focus();
return false;
}
}
}
}