Kala J
Kala J

Reputation: 2070

How to focus on input box when page loads?

I am trying to focus on the first text box, or input box, on my page when my page first loads. So I would like a blinking cursor to show up in the first text box when the page loads. I have googled numerous solutions that all resulted in the same: use .focus() agreement. I have tried but still doesn't work.

This is in my init function:

$(document).ready(function () {
                $('#TranslationTextBox:first').focus();
                $(".parametersNumericbox:first").focus();
            });

            $(".parametersNumericbox").focus(function () {
                var input = $(this);
                setTimeout(function () {
                    input.select();
                });
            });

Only when I tab several times does it take me to the first textbox.

EDIT: html code (using Kendo UI):

 <td id="TranslationTextBox">
                            @(Html.Kendo().NumericTextBoxFor<double>(model => model.Translation).Format("#").Decimals(0).Min(0)
                                  .HtmlAttributes(new { @class = "parametersNumericbox" })
                                  .Events(e => e
                                      .Change("TranslationTextBoxChanged")
                                      ))
                        </td>

The problem I am currently having is the focus appears to go to the buttons before the textfield on the page for some reason.

Upvotes: 0

Views: 3429

Answers (1)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

You can use Javascript, sure, but you can also use HTML:

<input type="text" autofocus>

In jQuery you could do:

$("input, textarea, select").filter(":first").focus();

A problem with your code seems to be that you are focussing several items. When you do that the item that was last focussed will get the focus.

Upvotes: 1

Related Questions