views:

268

answers:

2

Hello, I have a bunch of text boxes in my ASP.NET MVC view which are submitted to the server. How could I preserve the current focus so that the user can simply hit enter on any text box or click a submit button, and when the page returns (this is all via GET) the focus is where the user left off?

Thank you!

A: 

You would want to record the element with the focus, pass it to the controller, and then have the controller pass it back. Then some javascript would focus that element.

It appears there are a few ways to figure out and record which element has focus, none of them are great (see this hack http://trentrichardson.com/2008/05/24/an-attempt-to-find-focus/ or this plugin http://www.softwareunity.com/jquery/JQueryMoreSelectors/ (which does about the same thing)).

As best I can tell, there is no better way to do this.

James S
+2  A: 

You could simply use JQuery to set a hidden form field of the item that has focus.

<script type="text/javascript">
$(document).ready(function() {
    $("input").click(function() {
        $("#Focus").val = $(this).attr('id');
    });
});
</script>

<form action="#">
    <input id="Text1" type="text" />
    <input id="Text2" type="text" />
    <input id="Text3" type="text" />
    <input id="Text4" type="text" />
    <input id="Focus" type="hidden" />
</form>

Then all you need to do is pass it back to the page and set the focus

$("#<%= ViewData["Focus"] %>").focus();
Tony Borf