【问题标题】:asp.net text onkeyup eventasp.net 文本 onkeyup 事件
【发布时间】:2012-08-29 17:26:31
【问题描述】:

我对 asp.net 文本框的 onkeyup 事件有疑问。我要求在 asp.net 文本框中只允许十进制数字。为了实现这一点,我从 onkeyup 事件中调用了一个 java 脚本函数。 javascript 函数虽然正确验证了输入,但无法阻止用户输入字母或字母。一切都适用于 onkeychange 和 onkeypress 事件,只是它没有检测到退格键,这会导致错误计算依赖于此文本框值的边距百分比。

<asp:TextBox ID="txtListPrice" runat="server" CssClass="textbox" MaxLength="50" 
                                               onkeyup= "return IsNumberKey(event);" >      </asp:TextBox>
function IsNumberKey(evt) {

      //obj.value = obj.value.replace(/[^0-9]/g, "");
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode <= 31 || charCode == 46 || (charCode >= 48 && charCode <= 57)) {
        return CalculateMargin();
    }
    else {
        return false;
    }
}

 function CalculateMargin() 
{
    var ListPrice =  parseFloat(document.getElementById('<%=txtListPrice.ClientID%>').value);
    var Cost = parseFloat(document.getElementById('<%=txtCost.ClientID%>').value);
    var result = false;

    if (ListPrice != NaN && Cost != NaN)
    {
        if ((ListPrice != "" && Cost != ""))
        {
                var result = Math.round(((ListPrice - Cost) / (Cost)) * 100);
                document.getElementById('<%=txtMargin.ClientID%>').readOnly = false;
                document.getElementById('<%=txtMargin.ClientID%>').value = result;
                document.getElementById('<%=txtMargin.ClientID%>').readOnly = true;
                result = true;
        }
        else
            result = false;
    }
    return result;
}

谢谢

【问题讨论】:

    标签: c# javascript jquery asp.net c#-4.0


    【解决方案1】:

    OnKeyUp 事件的keycode 属性返回unicode 中按下的字符。您可以使用 javascript 警报查看退格键的值

    alert(event.keyCode);
    

    退格键是 unicode 8。您可以在 if 语句中使用它,然后按下退格键时您的 CalculateMargin 函数将运行。

    if (charCode <= 31 || charCode == 46 || (charCode >= 48 && charCode <= 57) 
        || charCode == 8)
    {
        return CalculateMargin();
    }
    

    在您的 else 语句中,在返回 false 之前,我会删除无效字符,方法是搜索字符串并删除任何不是数字的字符,或者删除字符串中的最后一个字符,理论上应该是有问题的字符。您可以使用 javascript slice 函数来执行此操作。

    else
    {
        var txtListPrice =  document.getElementById('<%=txtListPrice.ClientID%>');
        var txtValue = txtListPrice.value;
        txtListPrice.value = txtValue.slice(0, -1);
        return false
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多