使用 Enter 键提交表单

引言

最近在写 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盲,所以俺还是倾向与第二种方法啦。不多说了,今天很高兴,我的博客园排名杀进了前300名了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值