I've been more than familiar with detecting key presses in javascript for quite some time, and used to do it all the time in classic asp, but this time when I came to do it in the .net world, in was a little more involved.
This setup was also the first time I had to cope with Masterpages using AJAX inside them.
So, I have a simple content placeholder, inside this a textbox and these themselves are inside an updatepanel. I also have a modalpopup extender that shows whenever the page causes an update (asyncpostback).
So, to get this to work, I had to tie up my javascript with the ScriptManager.RegisterClientScriptBlock() method and placing the script into a LiteralControl that I had to place on the form also:
if(!Page.IsPostBack)
{
this.textBoxQuery.Attributes.Add("onkeypress", "javascript:return checkEnter(event);");
Page.RegisterHiddenField("__EVENTTARGET", textBoxQuery.ClientID);
string strScript = "function checkEnter(e){ " +
"var characterCode; " +
"if(e && e.which){ " +
"e = e; " +
"characterCode = e.which; " +
"} " +
"else { " +
"e = event; " +
"characterCode = e.keyCode; " +
"} " +
"if (characterCode == 13) " +
"{ " +
" " +
" document.getElementById('" + ButtonSearch.UniqueID + "').click(); " +
" return false; " +
"} " +
"else " +
"{ " +
" return true; " +
"}" +
"}";
ScriptManager.RegisterClientScriptBlock(LitScript, this.GetType(), "regScripts", strScript, true);
}
This now captures the enter key, and handles it as a normal button click event.
No comments:
Post a Comment