0

我有一个问题,将文本框中小数点后的值限制为 2。

我不想使用正则表达式。任何人都可以帮助我如何实现这一目标?

我不允许字符并将小数点限制为 1,

这是我的代码:

function CheckNumeric(e) {      
if (window.event) // IE 
    {
        if ((e.keyCode < 48 || e.keyCode > 57) & e.keyCode != 8 & !(e.keyCode == 46 && e.target.value.indexOf(".") == -1)) {
            event.returnValue = false;
            return false;
        }
    }
    else { // Fire Fox
        if ((e.which < 48 || e.which > 57) & e.which != 8 & !(e.which == 46 && e.target.value.indexOf(".") == -1)) {
            e.preventDefault();
            return false;
        }
    }
    }
  }

这是我的 HTML 代码:

 @Html.TextBox("CostperSeat", (object)item.CostperSeat, new{onkeypress="CheckNumeric(event); ", maxlength=10, style = "width:60px" })
4

1 回答 1

0

Please consider as below:

Textbox Control in .aspx page like as below:

<asp:TextBox ID="TextBox1" runat="server" Width="180px" onkeypress="return onlyDotsAndNumbers(this,event)"></asp:TextBox>

See, onkeypress event, call one of javascript function as below:

function onlyDotsAndNumbers(txt, event) {
    var charCode = (event.which) ? event.which : event.keyCode   
    if (charCode == 46) {
        if (txt.value.indexOf(".") < 0)
            return true;
        else
            return false;
    }

    if (txt.value.indexOf(".") > 0) {
        var txtlen = txt.value.length;
        var dotpos = txt.value.indexOf(".");
        if ((txtlen - dotpos) > 2)
            return false;
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

It would be helpful to you.

于 2013-07-15T13:36:59.723 回答