简体   繁体   中英

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.

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

        $(function () {
            $('#fooSearch').keyup(function () {
                $('#searchForm').submit();
            });
        });
    </script>

Can anyone help me to retain focus on the search textbox when the DOM is loaded?

To give the focus back to the searchbar, you can use jQuery's focus() , eg:

$("#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:

$('#fooSearch').keyup(function () {
    $('#searchForm').submit();
    $("#fooSearch").focus(); //focus back on the search bar
});

Otherwise, you will need to call focus() from an onload event:

$(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. 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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM