Q:

Move cursor to the end of textarea/input in form

I'm using this jQuery code to keep cursor at the end of textarea

jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    var $el = $(this),
      el = this;
    if (!$el.is(":focus")) {
      $el.focus();
    }
    if (el.setSelectionRange) {
      var len = $el.val().length * 2;
      setTimeout(function() {
        el.setSelectionRange(len, len);
      }, 1);
    } else {
      $el.val($el.val());
    }
    this.scrollTop = 999999;
  });
};
(function() {
  var searchInput = $(".search");
  searchInput
    .putCursorAtEnd()
    .on("focus", function() {
      searchInput.putCursorAtEnd()
    });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="mail.php" method="POST">
  <p>Name<input class="search" type="text" name="name" placeholder="Name">
    <p>Email</p> <input class="search" type="text" name="email" placeholder="Email">
    <p>Message for the author</p><textarea class="search" name="message" rows="6" cols="25" placeholder="Message"></textarea><br />
    <input type="submit" value="Send">
</form>

And it still doesn't do anything with the coursor position. Any suggestions?

A:

(function() {
  var searchInput = $(".search")
    .on("focus", function(e) {
      var $target = $(e.currentTarget);
      var len = $target.val().length;
      setTimeout(function() {
        $target[0].setSelectionRange(len,len);
      }, 1);
    });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="mail.php" method="POST">
  <p>Name<input class="search" type="text" name="name" placeholder="Name">
    <p>Email</p> <input class="search" type="text" name="email" placeholder="Email">
    <p>Message for the author</p><textarea class="search" name="message" rows="6" cols="25" placeholder="Message"></textarea><br />
    <input type="submit" value="Send">
</form>

You can just do : 
(function() {
  var searchInput = $(".search")
    .on("focus", function(e) {
      var $target = $(e.currentTarget);
      var len = $target.val().length;
      setTimeout(function() {
        $target[0].setSelectionRange(len,len);
      }, 1);
    });
})();

