The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.
Input Text focus() MethodThe focus() method is used to give focus to a text field. Tip: Use the blur() method to remove focus from a text field.
Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.
Set focus on the first text field:
$("input:text:visible:first").focus();
This also does the first text field, but you can change the [0] to another index:
$('input[@type="text"]')[0].focus();
Or, you can use the ID:
$("#someTextBox").focus();
You can use HTML5 autofocus
for this. You don't need jQuery or other JavaScript.
<input type="text" name="some_field" autofocus>
Note this will not work on IE9 and lower.
Sure:
<head>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#myTextBox").focus();
});
</script>
</head>
<body>
<input type="text" id="myTextBox">
</body>
Why is everybody using jQuery for something simple as this.
<body OnLoad="document.myform.mytextfield.focus();">
Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready()
function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.
You could check for this by adding onfocus
attributes in each of your <input>
elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:
var anyFieldReceivedFocus = false;
function fieldReceivedFocus() {
anyFieldReceivedFocus = true;
}
function focusFirstField() {
if (!anyFieldReceivedFocus) {
// Do jQuery focus stuff
}
}
<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">
HTML:
<input id="search" size="10" />
jQuery:
$("#search").focus();
Sorry for bumping an old question. I found this via google.
Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.
eg.
$('#myform input,#myform textarea').first().focus();
This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With