Skrubb
Skrubb

Reputation: 531

Setting default focus in mvc form using jQuery?

I have a page that has multiple tabs on it. Each tab is loaded using a partial view. I want to have the default focus go to the first "textbox" on each of these pages. Here is the problem I'm running into. I add this simple code:

<script type="text/javascript">
    $(document).ready(function () {
        $(function () {
            $("input[type=text]").first().focus();
        });
    });
</script>

I added this code to the layout master page thinking it would just default to the first text box on each page. That's not the case however. It will default to the first field on the first tab that loads, but when I navigate to a new tab, there is no focus, and when I navigate back to the first tab, still no focus. I have also added this simple code to each one of the partials, no luck there on setting the focus. I've also tried removing the "document.ready" part, no luck there. I've tried adding this to each individual page, in both ways described, no luck. Any ideas or thoughts?

Upvotes: 1

Views: 1142

Answers (2)

Skrubb
Skrubb

Reputation: 531

Actually, after reading the jQuery API documentation for tabs. I've come to the solution of using the "activate" event. So the code would look similar to this:

 $( ".selector" ).tabs({
activate: function( event, ui ) {}
});

And then the binding would look something like this:

$( ".selector" ).on( "tabsactivate", function( event, ui ) {} );

Thanks for the help though guys!

Upvotes: 0

knightsb
knightsb

Reputation: 347

the code you posted will run one time only and will choose the first input (with text type) he will encounter. you need to:

1)set a parent div for each tab content for example :

<div id='tab1Content'>
//you'r tab Content
</div>

2)bind a trigger for the tab switch, and in that delegate you will need to determine which tab has the focus, than use you'r original code in that way:

$('#tab1Content').find("input[type=text]").first().focus();

the id ('#tab1Content') will change acording to the focused tab.

Upvotes: 1

Related Questions