jQuery 将焦点和光标设置到文本输入字段/字符串 w 的末尾。查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19568041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:13:17  来源:igfitidea点击:

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

javascriptjqueryhtmlcss

提问by Mark

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:

当您单击要搜索的内容时,它会添加一个前缀。请参阅下面的 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>

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.

如何操作上述内容以将焦点放在#search 输入上,将胡萝卜(闪烁的文本插入光标)置于插入的文本/值的末尾?例如。

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

HC:<-- 添加到我的搜索输入中的值,我想在此处设置光标,紧跟在:

回答by pala?н

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

您可以使用Input.setSelectionRangeRange API 的一部分来执行此操作,用于与文本选择和文本光标交互:

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

演示:小提琴