Katastrophe: HTML Input (Autofocus) mit value. Focus an das ENDE des Input Feldes

Liebe Forengemeinde,

ich bin kein Freund von dem ganzen Javascript gedöns und vermutlich deshalb breche ich mir jedes mal die Finger wenn ich eine solche Funktion zum laufen bekommen soll.

Aber genug davon, ich möchte erstmal mein Problem darlegen: <input type="search" class="form-control form-control-lg" name="s" value="<?php echo $s ?>" autofocus id="search" /> Wie zu sehen ist haben wir ein Inputfeld mit Inhalt. Der durch Autofocus erzeugte Courser befindet sich nun nicht am Ende von Value sondern am Anfang. Das ist natürlich unschön.

Der Autofocus ist nicht definierbar. Jetzt muss also das übliche jquery gezauber die Funktion retten. Unter https://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/ bin ich auch fündig geworden. Ich bekomme es allerdings nicht zum laufen.

Mein Setting ist wirklich Simple:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" />

<script>
jQuery.fn.putCursorAtEnd = function() {

  return this.each(function() {
    
    // Cache references
    var $el = $(this),
        el = this;

    // Only focus if input isn't already
    if (!$el.is(":focus")) {
     $el.focus();
    }

    // If this function exists... (IE 9+)
    if (el.setSelectionRange) {

      // Double the length because Opera is inconsistent about whether a carriage return is one character or two.
      var len = $el.val().length * 2;
      
      // Timeout seems to be required for Blink
      setTimeout(function() {
        el.setSelectionRange(len, len);
      }, 1);
    
    } else {
      
      // As a fallback, replace the contents with itself
      // Doesn't work in Chrome, but Chrome supports setSelectionRange
      $el.val($el.val());
      
    }

    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Chrome)
    this.scrollTop = 999999;

  });

};
var searchInput = $("#search");

searchInput
  .putCursorAtEnd() // should be chainable
  .on("focus", function() { // could be on any event
    searchInput.putCursorAtEnd()
  });
</script>
<input type="search" class="form-control form-control-lg" name="s" value="Katastrophe" id="search" />

Wo ist denn jetzt mein Fehler?

    1. Hallo,

      danke für den Hinweis, leider ebenfalls ohne Änderung:

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" />
      
      <script>
      //usage
      moveCursorToEnd($('input'));
      
      function moveCursorToEnd(el) {
          if (typeof el.selectionStart == "number") {
              el.selectionStart = el.selectionEnd = el.value.length;
          } else if (typeof el.createTextRange != "undefined") {
              el.focus();
              var range = el.createTextRange();
              range.collapse(false);
              range.select();
          }
      }
      </script>
      <input type="search" class="form-control form-control-lg" name="s" value="Katastrophe" id="search" />
      
      1. hallo

        Hallo,

        danke für den Hinweis, leider ebenfalls ohne Änderung:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" />
        
        <script>
        //usage
        moveCursorToEnd($('input'));
        

        ist zu diesem Zeitpunkt das Element bereits im DOM?

        ... <input type="search" class="form-control form-control-lg" name="s" value="Katastrophe" id="search" />

        
        
        
        
      2. Hallo,

        danke für den Hinweis, leider ebenfalls ohne Änderung:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" />
        

        wird nicht mehr gebraucht. Ist "Vanilla-JS"

        //usage
        //moveCursorToEnd($('input'));
        
        function moveCursorToEnd(el) {
            if (typeof el.selectionStart == "number") {
                el.selectionStart = el.selectionEnd = el.value.length;
            } else if (typeof el.createTextRange != "undefined") {
                el.focus();
                var range = el.createTextRange();
                range.collapse(false);
                range.select();
            }
        }
        

        Dein DOM-Element hat die ID "search":

        <input type="search" class="form-control form-control-lg" name="s" value="Katastrophe" id="search" />
        

        Also musst Du zu einem geeignetem Zeitpunkt (onload?) folgendes feuern:

        var el = document.getElementById( "search" );
        moveCursorToEnd( el );
        
        1. Hinweis: Dieses Beispiel funktioniert NICHT wenn eine Konsole (WebIDE, Entwicklungswerkzeuge) offen ist:

          <html>
            <input type="search" class="form-control form-control-lg" name="s" value="Katastrophe" id="search" />
          	<script>
          		function moveCursorToEnd( el ) {
          			el.focus();
          			if ( typeof( el.selectionStart ) == "number" ) {
          				el.selectionStart = el.selectionEnd = el.value.length;
          			} else if (typeof el.createTextRange != "undefined") {
          				var range = el.createTextRange();
          				range.collapse( false );
          				range.select();
          			}
          		}
          		var el = document.getElementById( "search" );
          		moveCursorToEnd( el );
          	</script>
          </html>
          
          1. Vielen Dank, und frohe Weichnachten.

  1. hallo

    Da ist ein typischer Fall wo Tastaturen und Pointer-Devices verschiedene Strategien verlangen.

    Auf der Tastatur will ich eventuell den bestehenden Input selektiert, da ich mit Pfeiltaste sehr schnell den Cursor ans Ende setzen kann, oder andernfalls durch input den selektierten Text ersetze.

    Auf Pointer-Devices ist aber gerade dieses Bewegen des Cursors Übungssache.

    Ich habe da jetzt keine schnelle Lösung. Man könnte onfocus reagieren, wobei man eine eine js-medie-query konsultiert.

    Ich hege im übrigen Zweifel, ob autofocus auf einem Feld im Allgemeinen korrekt ist.