ASP.NET Core MVC: Unable to set focus on input element on view load

Stanislav Panferov 50 Reputation points
2023-09-24T21:57:19.01+00:00

I am trying to set focus using javascript on the first unfocused input element of MVC view in a load window event listener. But element is focused only after page reloading. Attached browser - MS Edge I tried reloading the page programmatically using window.location.reload, but it didn't have the same effect. Using setTimeout also was not helpful. This only works when previewing the page in Edge from Visual Studio. How to set focus correctly?

Test sample repo: https://github.com/pnfstas/TestFocus

HomeController:

using Microsoft.AspNetCore.Mvc;

namespace TestFocus.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Start()
        {
            return View("Start");
        }
    }
}

start.js:

start.js

Start.cshtml:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
	</head>
	<body>
		<form action="javascript:void(0);" method="post" style="width:500px;height:300px;display:flex;flex-direction:column;align-items:stretch;justify-content:space-between;">
			<fieldset style="flex:auto;display:flex;flex-direction:column;justify-content:space-evenly;">
				<legend>Authentication</legend>
				<label id="username-label" for="UserName">User name:</label>
				<input class="user-property-input" id="UserName" name="UserName" type="text" />
				<label id="email-label" for="Email">E-Mail:</label>
				<input class="user-property-input" id="Email" name="Email" type="email" />
				<label id="phone-label" for="PhoneNumber">Phone number:</label>
				<input class="user-property-input" id="PhoneNumber" name="PhoneNumber" type="tel" />
			</fieldset>
			<span id="test-focus-span" style="margin-top:15px;"></span>
		</form>
		<script id="start" src="~/src/start.js" asp-append-version="true"></script>
	</body>
</html>
Developer technologies ASP.NET ASP.NET Core
Microsoft 365 and Office Development Office JavaScript API
Developer technologies ASP.NET Other
{count} votes

3 answers

Sort by: Most helpful
  1. AddWebSolution 171 Reputation points
    2023-09-25T06:33:10.8866667+00:00

    Hi @Stanislav Panferov ,

    Here is your solution:

    https://stackoverflow.com/questions/4331022/focus-input-box-on-load

    OR

    You can also try this JavaScript function:

    document.addEventListener('DOMContentLoaded', function() {
        var inputs = document.getElementsByClassName('user-property-input');
    
        for (var i = 0; i < inputs.length; i++) {
            if (!inputs[i].matches(':focus')) {
                inputs[i].focus();
                break;
            }
        }
    });
    
    

    Make sure to include this JavaScript file in your HTML:

    <script id="start" src="~/src/start.js" asp-append-version="true"></script>

    Let us know if you need anything from our side.

    Best Regards,

    AddWebSolution

    1 person found this answer helpful.

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  3. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    2 deleted comments

    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.