javascript - Allow to enter only 2 decimal points number - Stack Overflow

I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and o

I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:

function isNumberKeyOnlyWithDecimalFormat(event,value,id){
        var val = value;
         if (event.shiftKey === true) {
                event.preventDefault();
        }
        if ((event.keyCode >= 48 && event.keyCode <= 57) ||
           (event.keyCode >= 96 && event.keyCode <= 105) ||
            event.keyCode == 8 || 
            event.keyCode == 9 ||  
            event.keyCode == 37 || 
            event.keyCode == 39 || 
            event.keyCode == 46 || 
            event.keyCode == 190) {

        } else {
            event.preventDefault();
        }
        if(val.indexOf('.') !== -1 && event.keyCode == 190){
            event.preventDefault();
        }
        if ((pointPos =   $('#'+id).val().indexOf('.')) >= 0){
            $('#'+id).attr("maxLength", pointPos+3);
        }
        else
            $('#'+id).removeAttr("maxLength");  
        }

It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?

I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:

function isNumberKeyOnlyWithDecimalFormat(event,value,id){
        var val = value;
         if (event.shiftKey === true) {
                event.preventDefault();
        }
        if ((event.keyCode >= 48 && event.keyCode <= 57) ||
           (event.keyCode >= 96 && event.keyCode <= 105) ||
            event.keyCode == 8 || 
            event.keyCode == 9 ||  
            event.keyCode == 37 || 
            event.keyCode == 39 || 
            event.keyCode == 46 || 
            event.keyCode == 190) {

        } else {
            event.preventDefault();
        }
        if(val.indexOf('.') !== -1 && event.keyCode == 190){
            event.preventDefault();
        }
        if ((pointPos =   $('#'+id).val().indexOf('.')) >= 0){
            $('#'+id).attr("maxLength", pointPos+3);
        }
        else
            $('#'+id).removeAttr("maxLength");  
        }

It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?

Share Improve this question edited Jul 29, 2013 at 5:39 felipsmartins 13.6k4 gold badges51 silver badges58 bronze badges asked Jul 29, 2013 at 5:25 nebulanebula 4,00213 gold badges55 silver badges83 bronze badges 4
  • Do you wan't to count how many decimals there are in the string? – iConnor Commented Jul 29, 2013 at 5:29
  • The function above restricts more than one decimal. – nebula Commented Jul 29, 2013 at 5:36
  • What? so you wan't to validate this 1.2.3 as true and 1.2.3.4 as false? – iConnor Commented Jul 29, 2013 at 5:38
  • yes, i want to validate the numbers as you said. 1.2.1 is invalid. 1.12 is valid and 1.112 is invalid. The function above does that. But the problem is while editing the previously entered number which is in the format 1123.12 – nebula Commented Jul 29, 2013 at 5:48
Add a ment  | 

5 Answers 5

Reset to default 3

Try this. It will check the value each time the focus is gone from the input field, but you can use any event you like. It will parse the value as a float, and then round it to 2 decimal points.

Here is the fiddle: http://jsfiddle/sAp9D/

HTML:

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

JavaScript:

var input_field = document.getElementById('the_id');

input_field.addEventListener('change', function() {
    var v = parseFloat(this.value);
    if (isNaN(v)) {
        this.value = '';
    } else {
        this.value = v.toFixed(2);
    }
});

Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this

if( value.match(/\./g).length === 2 ) {
    // Number has 2 decimals eg. 1.2.3
} else {
   // Number is incorrect eg. 1.2.3.4
}

or if you want 1.2 then

if( value.match(/\./g).length === 1 ) {
    // Code....
}

I use the following

// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
    strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;

if (whichCode == 13) return true;  // Enter
if (whichCode == 8) return true;  // Backspace
if (whichCode == 0) return true;  // Null
if (whichCode == 9) return true;  // Tab

key = String.fromCharCode(whichCode);  // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false;  // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
    var exp = /\./;
    var a = x.search(exp);
    if ( a != -1 ) return false;
}


}

// samer code on change  or on blur event
function allow2decimal(obj){
    var v = parseFloat($(obj).val());



        if (isNaN(v)) {
            $(obj).value = '';
        } else {
            newVal = v.toFixed(2);
            if(newVal >= 100){
                $(obj).val( 100 );
            }else{
                $(obj).val(newVal);
            }

        }

}
//usage
  <input
        onkeypress="return numericFormat( this , event , '.');"
        onchange="allow2decimal(this)"
        value="0.1"
        id="factory_silk" name="factory_silk" />
<html>
    <head>
        <script type="text/javascript">  
        function NumAndTwoDecimals(e, field) {  
        var val = field.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)) {  

        }  
        else {  
        val = re1.exec(val);  
        if (val) {  
        field.value = val[0];  
        }  
        else {  
        field.value = "";  
        }  
        }  
        }  
        </script>  
    </head>
    <body>
        <input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">  
    </body>
</html>
$('.number').keypress(function(evt){
    var str = $(this).val();
    var index = str.indexOf('.');
    if(index==-1){index=0;}else{index= index+1;}
    var extrapoint = str.indexOf('.',index);
    if(extrapoint>0){$(this).val(str.slice(0,-1));}
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
    var validNumber = new RegExp(/^\d*\.?\d*$/);
    var lastValid = $(this).val();
    if (validNumber.test($(this).val()))
    {
        lastValid = $(this).val();
    } 
    else
    {
        $(this).val(lastValid);
    }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744248633a4565058.html

相关推荐

  • javascript - Allow to enter only 2 decimal points number - Stack Overflow

    I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and o

    9天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信