KeyPress事件在asp.net内容页面中不起作用

时间:2014-03-16 09:28:24

标签: c# jquery asp.net

以下是我的代码。任何人请告诉我如何处理asp.net内容页面中的按键事件

<script type="text/javascript">
$(function () {
    $('#txtdesc').keypress(function (e) {
        var txt = $(this).val();
        if (txt.length > 5) {
            e.preventDefault();
        }
    });
});

<asp:TextBox ID="txtdesc" TextMode="MultiLine" runat="server" ></asp:TextBox>

2 个答案:

答案 0 :(得分:1)

$(function () {
    $('#<%=txtdesc.ClientID %>').on("keypress", function (e) {
        var txt = $(this).val();
        if (txt.length > 5) {
            alert('Hai');    
            e.preventDefault();
        }
    });
});

将ClienID与文本框控件一起使用,因为它是服务器控件。

答案 1 :(得分:0)

Asp.net在页面生成时更改HTML响应。 (对于网页控件),如下所示:

<input type="hidden" name="ctl00$txtdesc" id="**ctxxx_txtdesc**" />

所以,你应该使用asp.net生成的id属性值或class属性。像这样:

$('#ctl00$txtdesc').on("keypress", (function (e) {
   ...
});

<asp:TextBox ID="txtdesc" TextMode="MultiLine" CssClass="**txtdesc**" runat="server" ></asp:TextBox>

$('.txtdesc').on("keypress", (function (e) {
       ...
    });