Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only 2 decimal points entry to a textbox using jquery?

Allow only 2 decimal points when entering number to a textbox using jquery.

Please suggest any regex to allow only two decimal in textbox.

I have tried the following code.

$("#amountId").val().replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2');
like image 666
R J. Avatar asked Jun 13 '13 09:06

R J.


3 Answers

I was just testing using regex to learn it. But I recommend going with roasted's solution.

<input id="txtId" type="text"></input>

var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);

function myFunc(e) {
    var val = this.value;
    var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
    var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
    if (re.test(val)) {
        //do something here

    } else {
        val = re1.exec(val);
        if (val) {
            this.value = val[0];
        } else {
            this.value = "";
        }
    }
}

Working Fiddle

like image 111
Mr_Green Avatar answered Oct 23 '22 00:10

Mr_Green


You could do it without regex:

var dec = parseFloat($("#amountId").val(),10).toFixed(2);
like image 13
A. Wolff Avatar answered Oct 23 '22 01:10

A. Wolff


HTML:

<input type="text" class="maskedExt" maskedFormat="3,2" />
 maskedFormat="number count before decimal point, number count after decimal point"

Script:

$(document).ready(function () {
    $('body').on('keyup', '.maskedExt', function () {
        var num = $(this).attr("maskedFormat").toString().split(',');
        var regex = new RegExp("^\\d{0," + num[0] + "}(\\.\\d{0," + num[1] + "})?$");
        if (!regex.test(this.value)) {
            this.value = this.value.substring(0, this.value.length - 1);
        }
    });
});
like image 5
Vishal Surjuse Avatar answered Oct 23 '22 01:10

Vishal Surjuse