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

Beitrag lesen

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?