CodeSOD: Unable to Focus |
We've talked about Microsoft's WebForms in the past. Having used it extensively in the era, it was a weird mismatch, an attempt to get Visual Basic-style GUI designer tools attached to web applications, where button presses on the client side web page were exposed as events on the server side.
It also meant that you could manipulate the GUI objects on the server side, and the rendered HTML would represent that. So as part of processing a request, you might manipulate one of these "server side" controls. So, if you wanted to ensure that the search field had focus when the page loaded, you could simply invoke txtSearch.Focus()
as part of handling the request.
Since you may still need to do something on the client side at page load, like maybe register run some jQuery calls to turn a text box into a fancy date picker wideget, it also offered a ScriptManager.RegisterStartupScript
. This executes some JavaScript when the page loads.
If all of this sounds bad, and like it's the real WTF, you're absolutely right. But even in this terrible world, you could still make things worse.
Ino sends this:
private void SetFocus()
{
ScriptManager.RegisterStartupScript(hiddenDummy, hiddenDummy.GetType(), "focus",
"document.getElementById('" + txtSearch.ClientID + "').focus();", true);
ScriptManager.RegisterStartupScript(hiddenDummy, hiddenDummy.GetType(), "focus2",
"document.getElementById('" + txtSearch.ClientID + "').focus();", true);
ScriptManager.RegisterStartupScript(hiddenDummy, hiddenDummy.GetType(), "focus3",
"document.getElementById('" + txtSearch.ClientID + "').focus();", true);
ScriptManager.RegisterStartupScript(hiddenDummy, hiddenDummy.GetType(), "focus4",
"document.getElementById('" + txtSearch.ClientID +
"').value = document.getElementById('" + txtSearch.ClientID + "').value;", true);
ScriptManager.RegisterStartupScript(hiddenDummy, hiddenDummy.GetType(), "focus5",
"document.getElementById('" + txtSearch.ClientID +
"').value = document.getElementById('" + txtSearch.ClientID + "').value;", true);
}
Now, it's important to note that this is meant to run at page load. The goal is that the search box has focus after the initial load. Instead of using the server-side rendering to focus the text box, we'll use a client side script. We attach that script to hiddenDummy
, which is a hidden input field in this example which exists only because you need to supply a control that "owns" the
Комментировать | « Пред. запись — К дневнику — След. запись » | Страницы: [1] [Новые] |