Friday, May 9, 2014

How to set the cursor caret at the end of an input text field

As trivial as it sounds, ensuring that the cursor goes to the end of the text in an input field (particularly on an iOS device) is kind of tricky.

I tried dozens of ways involving .select(), .setSelectionRange(0,999), etc, etc. but what works is to simply remove the value from the input box and replace it in a few milliseconds.

So something like this:

  /////////////////////////////////////////////////////////////////////////////////////////
  // moveCaretToEndOfInputField - ensures that the cursor (caret) is at the end of the
  // ======================   text input field.
  /////////////////////////////////////////////////////////////////////////////////////////
  function moveCaretToEndOfInputField(oInputBox) {
    var tempValue = oInputBox.value;
    oInputBox.value = "";
    setTimeout(function() {
      oInputBox.value = tempValue;
    },1);

  }


moveCaretToEndOfInputField(this)">


No comments: