[英]Focus back on textbox after submitting using ASP.NET Core MVC
I am trying to introduce a dynamic search function in my project.我正在尝试在我的项目中引入动态搜索功能。 I have created a search form in my view which submits on
keyup
but the issue that I'm not facing is that when the view reloads, the text box is no longer in focus and so the user needs to click back onto it which obviously isn't ideal.我在我的视图中创建了一个在
keyup
上提交的搜索表单,但我没有面临的问题是,当视图重新加载时,文本框不再是焦点,因此用户需要重新单击它,这显然不是不理想。
My view is set up as follows:我的观点是这样设置的:
<form id="searchForm" asp-action="Index" method="get">
<div class="row">
<div class="col-9">
<input type="text" id="fooSearch" name="searchString" value="@ViewData["currentFilter"]" class="form-control" />
</div>
<div class="col-3">
<div class="row">
<div class="col-6">
<input type="submit" value="Search" class="btn btn-outline-secondary form-control" />
</div>
<div class="col-6">
<a asp-action="Index" asp-route-recent="true" class="btn btn-outline-secondary form-control">Recent</a>
</div>
</div>
</div>
</div>
</form>
with the following JQuery script to submit on keyup
使用以下 JQuery 脚本提交
keyup
$(function () {
$('#fooSearch').keyup(function () {
$('#searchForm').submit();
});
});
</script>
Can anyone help me to retain focus on the search textbox when the DOM is loaded?任何人都可以帮助我在加载 DOM 时将注意力集中在搜索文本框上吗?
To give the focus back to the searchbar, you can use jQuery's focus()
, eg:要将焦点返回到搜索栏,您可以使用 jQuery 的
focus()
,例如:
$("#fooSearch").focus();
Now, where you place this depends on whether your form submit is synchronous (and makes the page reload) or asynchronous.现在,你把它放在哪里取决于你的表单提交是同步的(并使页面重新加载)还是异步的。
If the submit is asynchronous, then you can place this in your keyup
event handler, right after the code that submits:如果提交是异步的,那么你可以把它放在你的
keyup
事件处理程序中, keyup
在提交的代码之后:
$('#fooSearch').keyup(function () {
$('#searchForm').submit();
$("#fooSearch").focus(); //focus back on the search bar
});
Otherwise, you will need to call focus()
from an onload
event:否则,您将需要从
onload
事件调用focus()
:
$(document).ready(function() {
$("#fooSearch").focus();
});
In all cases, first load or reload (submit), the focus should be on the search textbox so I think that you can just focus the textbox on load.在所有情况下,首先加载或重新加载(提交),重点应该放在搜索文本框上,所以我认为您可以将文本框放在加载上。
$(function() { $("#fooSearch").focus();});
The problem you may encouter is that the cursor will not be in the end of the keywords.您可能遇到的问题是光标不会位于关键字的末尾。 So I think that the best option here is to use Ajax to the update the results each time the user change the keywords.
所以我认为这里最好的选择是在用户每次更改关键字时使用 Ajax 来更新结果。 Maybe waiting a few seconds before each update is a good idea also.
也许在每次更新之前等待几秒钟也是一个好主意。
如果您使用的是 html5,您可以将自动对焦添加到您的 html 标签中,例如:
<input type="text" id="fooSearch" autofocus ="autofocus" name="searchString" value="@ViewData["currentFilter"]" class="form-control" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.