<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>
$("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', 2);
debugger;
// 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);
debugger;
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;
}
}
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.