2012-08-01

How to make asp:TextBox to enter only numbers and round up to two decimal points

With the use of two javascript functions, we can achieve this. First, we should prohibit the user from entering non numeric characters. For that, we can use the below javascript function

function isNumberKey(sender, evt) {
    var txt = sender.value;
    var dotcontainer = txt.split('.');
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (!(dotcontainer.length == 1 && charCode == 46) && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

This function will not allow user to enter anything other than numbers. So the ASPX markup of the textbox should looks like below

<asp:TextBox ID="txtTaxRate" runat="server" OnKeyPress="return isNumberKey(this, event);"></asp:TextBox>

Now, since we allow only numbers in that textbox, we can perform the round up operation for the value.

For that, we can use the below javascript function

function mathRoundForTaxes(source) {
    var txtBox = document.getElementById(source);
    var txt = txtBox.value;
    if (!isNaN(txt) && isFinite(txt) && txt.length != 0) {
       var rounded = Math.round(txt * 100) / 100;
       txtBox.value = rounded.toFixed(2);
    }
}

This function will round up the entered numeric value. So altogether, final markup for the textbox should looks like below

<asp:TextBox ID="txtTaxRate" runat="server" OnKeyPress="return isNumberKey(this, event);" onchange="mathRoundForTaxes(this.id);"></asp:TextBox>

1 comment:

Nur said...

Thanks. This was what i was looking for :)