Hi,
In the page I’m developing, I have two textboxes, and two CheckBoxLists. Each CheckBoxList is being populated according to what the user types in the respective TextBox. In the Page Load, I’m doing the following (VB.NET):

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   FirstTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & FirstTextBox.ClientID & "\',\'\')', 0)")
   FirstTextBox.Attributes.Add("onfocus", "javascript:setSelectionRange('" & FirstTextBox.ClientID & "','')")
   FirstTextBox.Focus()

   SecondTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & SecondTextBox.ClientID & "\',\'\')',0)")
   SecondTextBox.Attributes.Add("onfocus", "javascript:setSelectionRange('" & SecondTextBox.ClientID & "','')")
   SecondTextBox.Focus()
End Sub

The problem I’m having is that the user almost can’t type anything in the FirstTextBox because the focus goes to the SecondTextBox. What I would like to do is check if the focus is in the text box and then allow the code for this textbox. Something like: If (focus is on FirstTextBox) Then (do what is related to the FirstTextBox); If (focus is on the SecondTextBox) Then (do what is related to the SecondTextBox). Is this possible? What else can I do to make it work properly?

Thanks a lot,

Ana

Dani AI

Generated

Good diagnosis so far: the focus “bounces” because server code is setting focus more than once and the last call wins. spotted the ordering problem and improved things by consolidating handlers — that’s a solid quick fix. For a more robust, maintainable solution there are two practical patterns to consider: detect which control actually caused the postback on the server, or avoid full postbacks altogether by debouncing input and using AJAX/partial updates.

Server-side, read the postback source and run only the matching bind logic, then restore focus via a small client script. Example (VB.NET):

Dim target As String = Request.Form("__EVENTTARGET")
If Not String.IsNullOrEmpty(target) Then
  If target.IndexOf(FirstTextBox.UniqueID, StringComparison.OrdinalIgnoreCase) >= 0 Then
    BindFirstCheckBoxList()
    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "focus1",
      "document.getElementById('" & FirstTextBox.ClientID & "').focus();", True)
  ElseIf target.IndexOf(SecondTextBox.UniqueID, StringComparison.OrdinalIgnoreCase) >= 0 Then
    BindSecondCheckBoxList()
    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "focus2",
      "document.getElementById('" & SecondTextBox.ClientID & "').focus();", True)
  End If
End If

Client-side, prevent excessive postbacks and keep the UI responsive by debouncing the input and calling the server only after typing pauses. Either call a page WebMethod (JSON) and update the list in-place, or trigger a lightweight partial postback. Example debounce helper:

function debounce(fn, delay) {
  var t;
  return function () {
    var ctx = this, args = arguments;
    clearTimeout(t);
    t = setTimeout(function () { fn.apply(ctx, args); }, delay);
  };
}

Attach debounce to the input event, and prefer fetch()/WebMethod or an UpdatePanel trigger rather than heavy full-page postbacks. Additional tips: log Request.Form("__EVENTTARGET") in dev tools to confirm the source, avoid calling Focus() multiple times in Page_Load, and if you must preserve caret/selection save selectionStart before the postback and restore it with a small startup script after the update.

Consolidating handlers (what did) is good — for production consider the server-detection pattern above or move filtering to AJAX so focus and typing feel smooth.

Recommended Answers

All 6 Replies

Since the compiler runs in a top-down fashion, the last code executed on page load, is the setting of focus on textbox2. Which means textbox1 will not get focus unless you shift tab to it.

I think what you should do is just put the separate code fragments you want in the onfocus events for the respective textboxes. Just like you say in your algorithm:
=> sub txtbx1_focus() 'do code for txtbx1
=> sub txtbx2_focus() 'do code for txtbx2

Hi Wilch,

Thanks for your reply, but I don't understand how this solves my problem because, even if I put the code in two separated code fragments I need to call them on the Page Load (I'm populating the checkBoxList using the TextBox.TextChanged event and the line

TextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & FirstTextBox.ClientID & "\',\'\')', 0)")

in the Page_Load is doing a post back, so the CheckBoxList can be updated to match the text in the TextBox).
Could you please explain me more?

Thanks a lot.

I have replaced textbx2.focus with txtbx1.focus

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   FirstTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & FirstTextBox.ClientID & "\',\'\')', 0)")
   FirstTextBox.Attributes.Add("onfocus", "javascript:setSelectionRange('" & FirstTextBox.ClientID & "','')")
 

   SecondTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & SecondTextBox.ClientID & "\',\'\')',0)")
   SecondTextBox.Attributes.Add("onfocus", "javascript:setSelectionRange('" & SecondTextBox.ClientID & "','')")
  
  FirstTextBox.Focus()

End Sub

Then in your javascript function: setSelectionRange check which textbox has focus and do the appropriate.
That's what i would try to do !

This solution takes me back to the source of my problem: I don't know how to check where the focus is. Do you know how can we do this (in VB.NET, C#.NET or javascript)?

Thanks.

How about this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 FirstTextBox.Attributes.Add("id", "txtbx1") 
  FirstTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & FirstTextBox.ClientID & "\',\'\')', 0)")
   FirstTextBox.Attributes.Add("onfocus", "javascript:setSelectionRange('" & FirstTextBox.ClientID & "','','txtbx1')")
 
 FirstTextBox.Attributes.Add("id", "txtbx2") 
   SecondTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & SecondTextBox.ClientID & "\',\'\')',0)")
   SecondTextBox.Attributes.Add("onfocus", "javascript:setSelectionRange('" & SecondTextBox.ClientID & "','','txtbx2')")
  
  FirstTextBox.Focus()

End Sub

<script language="javascript">
function setSelectionRange(param1, param2, param3){
  if(param3 == "txtbx1") //do code for txtbx 1
  if(param3 == "txtbx2") //do code for txtbx 2
}
</script>

Doing it this way you wont have to check which txtbx has focus, but actually you pass the txtbxid to the function, everytime the txtbx gains focus, and do your code depending on the identity of the txtbx.

Hi Wilch,

Thanks a lot for you quick replies. I appreciate it.
I didn't try your suggestions because the code I had for the textBoxes was the TextBox.Attributes.Add(...) stuff and I'm not sure if we can do this with javascript.

However, I found a way to solve my problem. I was using two different routines for the textChanged event, one for each textBox. I changed my code and both textBoxes are calling the same routine and what I'm doing is similar to the folowing code:

Protected Sub myTextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim currentTextBox As TextBox = DirectCast(sender, TextBox)
    Dim clientId As String = currentTextBox.ClientID.ToString()
    If clientId.Contains("FirstTextBox") Then
       BindFirstCBL()
       FirstTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & FirstTextBox.ClientID & "\',\'\')', 500)")
       FirstTextBox.Attributes.Add("onfocus", "javascript:setSelectionRange('" & FirstTextBox.ClientID & "','')")
       'if user clicks on SecondTextBox, change the focus to SecondTextBox
       SecondTextBox.Attributes.Add("onclick", "javascript:setFocus('" & SecondTextBox.ClientID & "','')")
       FirstTextBox.Focus()
            
   ElseIf clientId.Contains("SecondTextBox") Then
       BindSecondCBL()
       SecondTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & SecondTextBox.ClientID & "\',\'\')', 2000)")
       SecondTextBox.Attributes.Add("onfocus", "javascript:setSelectionRange('" & SecondTextBox.ClientID & "','')")
       'if user clicks on FirstTextBox, set the focus to FirstTextBox
       FirstTextBox.Attributes.Add("onclick", "javascript:setFocus('" & FirstTextBox.ClientID & "','')")
       SecondTextBox.Focus()
            
   End If
End Sub

Basically what I'm doing is checking if the sender is FirstTextBox or SecondTextBox and based on this, executing the corresponding code. If the user clicks on the other TextBox, the focus is changed too.

And in the Page_Load I have the following:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        FirstTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & FirstTextBox.ClientID & "\',\'\')', 500)")
        SecondTextBox.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'" & SecondTextBox.ClientID & "\',\'\')', 2000)")
End Sub

Well, I think everything is working well now =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.