Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofocus on EditorFor

I would like to autofocus on an editorfor in my application, but I can't seem to do that. I have successfully used autofocus on a textbox, but I would like to use an editorfor to keep my application's look universal.

Any solutions to this would be much appreciated, thank you.

My attempt:

@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" }, autofocus = "" })
like image 350
Jon Avatar asked Aug 23 '15 16:08

Jon


4 Answers

This s because you are using EditorFor instead of something specific like TextBoxFor.

@Html.TextBoxFor(model => model.Name, new { htmlAttributes = new { 
                    @class = "form-control" }, autofocus="autofocus"})

Or you can do that using jQuery:

<div class="editor-field focus">
    @Html.EditorFor(model => model.Description)
    @Html.ValidationMessageFor(model => model.Description)
</div> 
$(function() {
    $('.focus :input').focus();
});

Update:
As you know TextBoxFor always creates a textbox with type input, But EditorFor is a little bit smart, it renders markup based on the datatype of the property.

like image 179
Sirwan Afifi Avatar answered Nov 16 '22 02:11

Sirwan Afifi


Using .Net Framework 4.5 and MVC 5, this works for me:

@Html.EditorFor(model => model.Description, new {
    htmlAttributes = new {
        @class = "form-control",
        autofocus = true
    }
})
like image 36
Patrick Avatar answered Nov 16 '22 00:11

Patrick


You put the autofocus attribute in the wrong spot.

@Html.EditorFor(model => model.Description, 
     new { htmlAttributes = new { @class = "form-control" }, autofocus = "" })

Try this instead:

@Html.EditorFor(model => model.Description, 
     new { htmlAttributes = new { @class = "form-control", autofocus = "" } })
like image 3
Steve M Avatar answered Nov 16 '22 00:11

Steve M


I've been following this thread and I may have stumbled on an answer to your question about autofocus on EditorFor - this is all Asp.Net 4.5 and MVC 5, not that it matters.

  1. In the Scripts folder I have a jQuery script file:

    $(function(){ $('.someclassname').focus(); });

I add the script name to the BundleConfig and render it in the view.

  1. In the view I add the classname to the EditorFor <div class="col-md-10" someclassname">
  2. I then add the type="text" autofocus="autofocus" to the EditorFor's @class. So, new{@class="form-control", type="text", autofocus="autofocus"
  3. That's pretty much it, when the DOM loads the .someclassname field gets the cursor focus... PS. In fact if you just do (3) it works also...
like image 1
Eric Chow Avatar answered Nov 16 '22 02:11

Eric Chow