1

I'm working on an MVC project and am trying to set the focus on this:

<td><%=Html.TextBoxFor(de => Model.EmailAddress1)%></td>

My jquery is in the same view near the top of the page:

<script type="text/javascript">
    $(document).ready(function () {
        $("[id$=MainContent_EmailAddress1").focus();
        $("#EmailAddress1").focus();
    });
</script>

I've tried a few combinations to set the focus to this box but nothing I've tried works. Can anyone help?

2
  • 2
    Can you post the generated HTML? Commented Apr 19, 2013 at 21:03
  • It's not depending of your ASP MVC, it's purely depending of the rendered DOM structure ! Get it with "View source code" or a console, then you will know what to bind ! Commented Apr 19, 2013 at 21:03

1 Answer 1

1

You could take several steps in solving your problem. First of all, load your html and see, weather the id being rendered matches with the one that you provided. Secondly, I'd rather suggest you more rigid way to capture the element, or control the output.

You could add an extra functional class to grab the element

Html.TextBoxFor(x => x.EmailAddress1, new { @class = "fHandleClass" });

and the script

<script type="text/javascript">
//<![CDATA[
  $(function(){
      $(".fHandleClass").focus();
  });
//]]>
</script>

Or you could directly control the id

Html.TextBoxFor(x => x.EmailAddress1, new { id = "MyExactId" });

and the script

<script type="text/javascript">
//<![CDATA[
  $(function(){
      $("#MyExactId").focus();
  });
//]]>
</script>

And finally, I suggest you to switch to razor view engine. It is much better, the Web forms view engine were designed to be understood by the designers, it is not very friendly for handwriting. Razor was specifically designed for being written by hand.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, maybe we should get Razor. Unfortunately, none of your suggestions worked. I was hoping changing the id would work at least.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.