The Issue
The comboBox has a couple of server side events to deal with field changing.
- OnSelectedIndexChanged
- OnTextChanged
How can we catch the comboBox changing on the client side?
The Solution
Without access to these function on the client side, we need to use the client side events of the textBox that is contained within the comboBox. As with any textBox this one also has the onChange event, but the event does not run when the text was changed and the focus moved to another field. There are a few options:
- onKeyPress
- onKeyUp
- onBlur
The problem with onKeyPress is when it gets to the javascript function the value of the textBox is has not changed yet, leaving onKeyUp and onBlur. While onKeyUp will give the desired effect when the user presses a key on the keyboard, part of the point of a comboBox is the ability to use the mouse, which will not be captured by this event, leaving onBlur as the remaining option. It’s still not perfect, since the event won’t run until the focus is moved off the comboBox, but it appears to be the best option. In some cases you may want to use both onKeyUp and onBlur to get the best of both events, but be careful because when the user uses the keyboard and the moves the focus your event will run twice.
In the example below I have a comboBox named cmbExample and a javascript function that accepts the textBox calling it as a parameter, cmbExample_OnBlur(textBox). I add the onBlur event to the textBox in the Page_Load method in the code behind.
protected void Page_Load(object sender, EventArgs e)
{
TextBox textBox = cmbExample.FindControl("TextBox") as TextBox;
if (textBox != null)
{
textBox.Attributes.Add("onBlur", "cmbExample_OnBlur(this);");
}
} |