将焦点和光标设置为文本结束输入字段/字符串w。 Jquery [英] Set focus and cursor to end of text input field / string w. Jquery
问题描述
我有以下函数将一个选择器添加到搜索输入作为高级选项,就像堆栈溢出高级搜索。
当你点击你正在搜索因为它添加了一个前缀。请参阅下面的Jquery:
< 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>
如何操作上面的内容也可以将焦点放到#search输入中,将胡萝卜闪烁文本插入光标)到插入的文本/值的末尾?
eg。
HC:< - 添加到我的搜索输入的值,我想把光标放在这里: p>
您可以使用 Input.setSelectionRange
,用于与文本选择和文本光标进行交互的Range API的一部分:
var searchInput = $('#Search');
//乘以2,以确保光标总是结束;
// Opera有时会看到回车为2个字符。
var strLength = searchInput.val()。length * 2;
searchInput.focus();
searchInput [0] .setSelectionRange(strLength,strLength);
演示: Fiddle
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 :
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
这篇关于将焦点和光标设置为文本结束输入字段/字符串w。 Jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!