How to change the visible text in a narrow input element to see the cursor at the end?

The problem that I am facing is that given the input element with maxlength, which is much wider than the width of the element (as set in its style), and given the value which is wider than the width of the element, how can I get the scroll element to the end of the text. In IE, this is easy, I create a textRange object, put its start and end position at the end of the text, select a call in this range and bam, the cursor is placed at the end of the text And the text is moved so that the end is shown. In Firefox, Chrome, Safari trying to use the setSelectionRange input element sets the cursor to the correct position, but the text does not move so that I see its end, but instead the beginning. Does anyone know how I could put the cursor at the end of the text AND move the text so that I can see the cursor?

Thank!

Shane


<html>
  <head>
    <title>input cursor position</title>
    <script language='javascript'>
      function setCursor()
      {
         var objInput = document.getElementById( 'testinputbox' );
         var nLength = objInput.value.length;

         objInput.focus();
         objInput.setSelectionRange( nLength, nLength );
      }
    </script>
  </head>
  <body onload='setCursor();'>
    <input id='testinputbox' maxlength='200' value='some very very very very very long text' style='width: 100px;'></input>
  </body>
</html>
+3
2

, - , , Firefox. , , .

function setCursor(id)
{
    var elem = document.getElementById(id);

    elem.focus();
    elem.setSelectionRange(elem.value.length, elem.value.length);

    // Trigger a "space" keypress.
    var evt = document.createEvent("KeyboardEvent");
    evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 0, 32);
    elem.dispatchEvent(evt);

    // Trigger a "backspace" keypress.
    evt = document.createEvent("KeyboardEvent");
    evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 8, 0);
    elem.dispatchEvent(evt);
}

initKeyEvent .

+7

kludge, :

: , :

<html>
  <head>
    <title>input cursor position</title>
    <script language='javascript'>
function setatend() {
    var save = document.getElementById("mytextbox").value;
    mytextbox.focus(); 
    mytextbox.value = save; 
}
function setfocus() {
    var box = document.getElementById("mytextbox");
    box.focus();    
}
</script>
  </head>
      <body onload='setfocus();'>
    <input onfocus='setatend();' id='mytextbox' maxlength='200' value='some very very very very very long text' style='width: 100px;'></input>
  </body>
</html> 
+1

All Articles