Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Mvc - Html.TextBox - Set Autofocus property

In Html 5, there is a new attribute on textbox called autofocus.

The problem is that it is a boolean value (there or not there)

It should look something like :

<input name="a" value="" autofocus>

I tried :

<%= Html.TextBox( "a", null, new { autofocus } ) %>

But, it gives me an error because I'm not setting a value to autofocus...

I know I can do it manually, but can I do it with Html.TextBox ?

like image 519
Melursus Avatar asked Jun 08 '10 14:06

Melursus


2 Answers

Try <%= Html.TextBox( "a", null, new { autofocus = "" } ) %>

According to the HTML5 spec on boolean attributes:

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

So either

  • <input name="a" value="" autofocus> or
  • <input name="a" value="" autofocus=""> or
  • <input name="a" value="" autofocus="autofocus">

should be valid.

like image 177
Bradley Mountford Avatar answered Sep 18 '22 07:09

Bradley Mountford


As of XHTML, the standard way to enable such a boolean attribute would be:

<input name="a" value="" autofocus="autofocus" />

therefore, assuming that is still valid in HTML5, you could use the following code:

<%=Html.TextBox( "a", null, new { autofocus: "autofocus" } ) %>
like image 27
LorenzCK Avatar answered Sep 19 '22 07:09

LorenzCK