Timmy Von Heiss Timmy Von Heiss - 3 months ago 18
Javascript Question

set mouse focus and move the cursor to the end of the input focus in a Rails js.erb

I have seen this topic, set-mouse-focus-and-move-cursor-to-end-of-input-using-jquery but I cannot get it to work.

comments/edit.js.erb

def edit
@comment = Comment.find(params[:id])
respond_to do |format|
format.js
format.html
end
end

<%= form_for @comment, url: photo_comment_path(@comment.photo_id, @comment), method: :patch, remote: true do |f| %>
<%= f.text_field :content %>
<%= f.submit class: "hidden" %>
<% end %>


Rails automatically moves
:content
into the
input#comment_content
. If I call

$("input#comment_content").focus()


this brings the cursor into focus at the beginning of the string. I want it at the end of the string.

I have tried the following and several other combinations but nothing sticks:

var this = $('input#comment_content').val();
$('input#comment_content').val('');
$('input#comment_content').focus();
$('input#comment_content').val(this);

Answer

I finally got this to work, but it only works one way. You have to add a custom class to the input field and then use that as 'input#comment_content.class'

Comments