Sometimes we need to postback to server & execute a particular event if user hit the enter key after filling the textbox. For this we need to associate our text box control with a button we want to execute as if we clicked on the button.
* For this we can call a javascript function which will force the button click event
* Call the click event of the button if enter key is pressed.
* Register the javascript function for the controls
This is checked in firefox,IE & Chrome and is working correctly.
C# Code
-----------
protected void Page_Load(object sender, EventArgs e) { txtProductName.Attributes.Add("onkeypress", "return AutoPostBackOnEnterKey(event,'" + btnSearch.ClientID + "')"); txtProductID.Attributes.Add("onkeypress", "return AutoPostBackOnEnterKey(event,'" + btnSearchByProductID.ClientID + "')"); } protected void btnSearch_Click(object sender, EventArgs e) { //Code } protected void btnSearchByProductID_Click(object sender, EventArgs e) { //Code }Javascript Function --------------------function AutoPostBackOnEnterKey(e, buttonid) { var evt = e ? e : window.event; var bt = document.getElementById(buttonid); if (bt) { if (evt.keyCode == 13) { bt.click(); return false; } } }
When you press a key on your keyboard, the js OnKeyPress event is fired. This calls a function to which we pass the id of the button associated with the TextBox. The function gets a reference to the button and simuilates a mouse-click on the Button. We perform a browser detection because IE and Netscape have different event models. The function finally returns false so that the keypress event is cancelled (otherwise a second form submit will be raised)
Works in following
Code & Idea is from here
0 comments:
Post a Comment