Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery how to set input focus on control

Tags:

Hey I am very new to jquery using asp.net, and I was wondering how to set focus on a textbox using jquery.

I have my script in my HeaderContent but it is not working, no focus on load. And yes I know this can be done on the server side as well, but I am just trying to get better and more familiar with jquery. Thanks.

<script type="text/javascript">    $(document).ready(function () {       $("#MainContent_LoginUser_UserName").focus();    }); </script> 
like image 362
user516883 Avatar asked Jan 10 '11 22:01

user516883


People also ask

How do you set focus on input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

How will you focus on the input field when the page is loaded?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.

Is Focus deprecated in jQuery?

focus() method may not fail directly, as the method still exists. However, the expected behavior will not occur. This method is deprecated.


1 Answers

Your code is correct. If it is failing, chances are $("#MainContent_LoginUser_UserName") is not the correct selector value or perhaps jQuery is not correctly loaded.

If you are using jQuery alongside standard ASP.NET JavaScript, then the '$' will not be mapped to jQuery, but instead to ASP.NET's JavaScript framework. You may need to substitute $("#foo") for jQuery("#foo").

like image 139
Nathan Taylor Avatar answered Oct 07 '22 16:10

Nathan Taylor