HTML Textbox force 2 decimal places with JavaScript

Created by
Thursday, August 4, 2016

 

I was recently working on a project that required me to force decimal values on user input. While i did round off numbers in the back end i also wanted to deny a user from entering false data via the form.

Example: $105.039 - Round to $105.04

To achieve this i used a relatively simple javascript function to check on keychange a count of values past the period on user input.

Let's begin with a simple ASP.NET textbox

@Html.TextBox("StudentName", null, new { @class = "form-control" })  

What we want to do now is add in an onkeypress control and have it call a javascript function.

@Html.TextBox("StudentName", null, new { @class = "form-control", onkeypress = "return validateDecimalValue(this, event);" })  

With this function "validateDecimalValue" we are going to check the user input before any submit events happen. This will prevent the client from entering in any value with more than two digits past the decimal place

// Validate decimal input on given textbox
function validateDecimalValue(element, event) {
    var charachterCode = (event.which) ? event.which : event.keyCode;
    var number = element.value.split('.');

    // characterCode 46: period
    // characterCode 31: unit seperator
    // characterCode 48: digit 0
    // characterCode 57: digit 9

    if (charachterCode != 46 && charachterCode > 31 && (charachterCode < 48 || charachterCode > 57)) {
        return false;
    }

    // Just one period
    if (number.length > 1 && charachterCode == 46) {
        return false;
    }

    // Get the carat position
    var caratPosition = getSelectionStart(element);

    var dotPosition = element.value.indexOf(".");

    if (caratPosition > dotPosition && dotPosition > -1 && (number[1].length > 1)) {
        return false;
    }
    return true;
}

function getSelectionStart(e) {
    if (e.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd('character', e.value.length);

        if (r.text === '') return e.value.length;
        return e.value.lastIndexOf(r.text);
    } else return e.selectionStart;
}

 

This function should be relatively easy to understand as your read through it! Take a look at the w3schools HTML ASCII Charachter reference to understand more.

 

0
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
0 comments