Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus and cursor to end of text input field / string w. Jquery [duplicate]

I have the following function that adds a selector to a search input as an advanced option, just like stack overflows advanced search.

When you click what you are searching for it adds a prefix. See Jquery below:

<script> $(document).ready(function () {          $("table#advanced_search_options tr").click(function () {             var SearchSelection = $(this).children("td:last-of-type").html();             var SearchInput = $('#Search');             SearchInput.val(SearchInput.val() + SearchSelection);             return false;             alert(SearchSelection);         }); }); </script> 

How can I manipulate the above to also bring focus to the #search input, placing the carrot (the blinking text insert cursor) to the end of the inserted text/value? eg.

HC: <-- The added value to my search input, I would like to set the cursor here, right after the :

like image 837
Mark Avatar asked Oct 24 '13 13:10

Mark


People also ask

How do you move the cursor to the end of Contenteditable entity?

createTextRange();//Create a range (a range is a like the selection but invisible) range. moveToElementText(contentEditableElement);//Select the entire contents of the element with the range range. collapse(false);//collapse the range to the end point.

How do I move focus to next input with jQuery?

attr('type') === 'text') { $(this). next(inputs). focus(); return false; } }); If a user clicks on an input that already has a value it will override it, instead of going to the next input, it will also only focus on text inputs.

How do you focus an element in jQuery?

The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.


1 Answers

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');  // Multiply by 2 to ensure the cursor always ends up at the end; // Opera sometimes sees a carriage return as 2 characters. var strLength = searchInput.val().length * 2;  searchInput.focus(); searchInput[0].setSelectionRange(strLength, strLength); 

Demo: Fiddle

like image 157
palaѕн Avatar answered Oct 14 '22 20:10

palaѕн