Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  98] [ 1]  / answers: 1 / hits: 116539  / 11 Years ago, thu, october 24, 2013, 12:00:00

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 :


More From » jquery

 Answers
20

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


[#74763] Wednesday, October 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dontaemauricioc

Total Points: 456
Total Questions: 84
Total Answers: 99

Location: Puerto Rico
Member since Fri, Oct 14, 2022
2 Years ago
;