引言

最近在写 TrueLove 的时候需要添加酒店,想实现那种和豆瓣差不多的使用 Enter 键来提交表单添加酒店。翻阅了 CodeProject 和 123ASPX 的文章,找了两种方法,下面来简单介绍以下。

使用 JS 代码

我们在表单里面的 TextBox (asp.net控件),然后在里面添加 attributes 响应对 JS 函数处理。具体我也不知道怎么说,看看代码就了解了。

 

Default.cs 
//Add the javascript so we know where we want the enter key press to go
if (!IsPostBack)
{
txtboxFirstName.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
txtboxLastName.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
txtboxAddress1.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
txtboxAddress2.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
txtboxCity.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
txtboxState.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
txtboxZipcode.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
}

然后在default.aspx的页面里面写入下面的js代码:

default.aspx 
<SCRIPT type=text/javascript>
function doClick(buttonName,e)
{
//the purpose of this function is to allow the enter key to 
//point to the correct button to click.
var key;
if(window.event)
key = window.event.keyCode;     //IE
else
key = e.which;     //firefox
if (key == 13)
{
//Get the button the user wants to have clicked
var btn = document.getElementById(buttonName);
if (btn != null)
{ //If we find the button click it
btn.click();
event.keyCode = 0
}
}
}
</SCRIPT>

使用 Panel 来实现

panel 的实现方法实现起来很简单,不用写任何一行代码。把我们的 TextBox 放到 panel 控件里面,然后设置 panel 控件的 defaultbutton 的属性为我们要响应的那个button的id。

<asp:Panel ID="panSearch" runat="server" DefaultButton="btnSearch2" Width="100%" >

只需要这样就ok了,哈哈,很简单...

总结

这两种方法根据你自己的喜好来使用,也许你的js水平很高,那么第一种方法很适合你,我是基本上的js盲,所以俺还是倾向与第二种方法啦。

   function fnTrapKD(btn,evt)
   {
                //Firefox
                if( evt != window.event && evt.which == 13)
                {
                    evt.returnValue=false;
     evt.cancel = true;
                    btn.click();                   
                }
                //IE
                else if(window.event.keyCode == 13)
                {
                    event.returnValue=false;
     event.cancel = true;
                    btn.click();
                }
   }

onkeydown="javascript:fnTrapKD(document.all.quickquery,event)"

posted on 2007-09-11 16:35  大口仔  阅读(366)  评论(0编辑  收藏  举报

使用Live Messenger联系我
关闭