tags:

views:

152

answers:

1

I am trying to set a focus on a dropdown within GridView(gridViewDropDown class) when page loads:

if ($('select.gridViewDropDown').length)
{
     alert("Found my dropdown");
        //$('select.gridViewDropDown:first').focus();
     setTimeout(function() { $('select.gridViewDropDown').focus(); }, 10);
}

I can see the alert which means that dropdown is found but it never gets a focus. What do I need to change here? I am using IE 6/7.

+1  A: 

I'd try this approach:

$(function() {
  setTimeout(function() { $('select.gridViewDropDown').focus(); }, 50);
});

You need to wait until the DOM is ready, it's possible that something else is set to steal focus when the page loads (code that's most likely executing when the DOM's ready as well) This approach times it to be just slightly after that happens.

It also takes advantage of how jQuery works, if no elements are found when this function fires, none will steal focus, so it's safe to just leave in there as-is.

Nick Craver
@Nick, Thanks, should I do it on a master page or a content page or doesn't matter?
Victor
@VictorS - Doesn't matter...it's all rendered to the client as one page, putting it in the master if used on multiple pages, otherwise stick it in the content page.
Nick Craver
@Nick Still doesn't get a focus. Can I send that dropdown "Tab" key?
Victor
@Nick Or, do something like this?`$('select.gridViewDropDown').trigger('focus');`
Victor
@Nick Looks like `$('select.gridViewDropDown').trigger('focus');` works while `$('select.gridViewDropDown').focus();` doesn't, don't know why
Victor
@VictorS - Something else is going on there, not sure what, are there other focus events attached?
Nick Craver
@Nick Think I have an idea but I have to keep that other stuff so I will use `trigger` for now.
Victor
@VictorS - If it works then I see no reason not to leave it using `.trigger()`, I am curious what causes the other handler to interfere though.
Nick Craver
@Nick - Looks like other developers tried to use REQUEST_LASTFOCUS field to restore focus between postbacks.
Victor
@Nick Turns out `focus()` doesn't bubble in IE so that was a problem. Why `trigger` works then I don't know
Victor