Restrict to 2 decimal places in keypress of a text

2019-01-22 13:04发布

I want to enter a decimal point in a text box. I want to restrict the user by entering more than 2 digits after the decimal point. I have written the code for achieving that in the Keypress event.

function validateFloatKeyPress(el, evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;

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

    if (charCode == 46 && el.value.indexOf(".") !== -1) {
        return false;
    }

    if (el.value.indexOf(".") !== -1)
    {
        var range = document.selection.createRange();

        if (range.text != ""){
        }
        else
        {
            var number = el.value.split('.');
            if (number.length == 2 && number[1].length > 1)
                return false;
        }
    }

    return true;
}
<asp:TextBox ID="txtTeamSizeCount" runat="server" onkeypress="return validateFloatKeyPress(this,event);" Width="100px" MaxLength="6"></asp:TextBox>

The code is working but the issue is: if I enter ".75" and then change it to "1.75", it is not possible. Only way to do it is delete it completely and then type "1.75". This issue occurs if there are already 2 digits after decimal in the textbox. The conditions that I impose are

a) After decimal is present, it must at least have 1 or 2 digits. For ex .75 or .7 or 10.75 or 333.55 or 333.2 is accepted. but not .753 or 12.3335


b) Before the decimal, it not a must for the user to enter a value. User must also be able to enter integer numbers also.

Can you tell me what could be the issue?

Thanks,
Jollyguy

7条回答
Viruses.
2楼-- · 2019-01-22 13:44
1.)No multiple decimals points.
2.)Two numbers after decimal point.
3.)Allow only Numbers and one decimal point(.).

This will help.jsFiddle

查看更多
Juvenile、少年°
3楼-- · 2019-01-22 13:46

You can do it by another way with onchange event, to not restrict to user to type, rather just convert number after typing, to make uniform, like this,

function validateFloatKeyPress(el) {
    var v = parseFloat(el.value);
    el.value = (isNaN(v)) ? '' : v.toFixed(2);
}
<input id="aninput" type="text" onchange="validateFloatKeyPress(this);" />

45.846 should be 45.85 but in your code user needed to convert their-self and then they will type 45.85 directly

查看更多
神经病院院长
4楼-- · 2019-01-22 13:46

this code is very complet, I change "." to ",":

  • can't "," in begin
  • can't write more ","

    <script type="text/javascript">
    
        function isNumberKey(evt, el) {
            var charCode = (evt.which) ? evt.which : event.keyCode;
            var number = el.value.split(',');
            var caracter = el.value;
    
            if (charCode != 44 && charCode > 31 && (charCode < 48 || charCode > 57)) {
                return false;
            }
    
            if (charCode == 44 && caracter == "") {
                return false;
            }
    
            if (charCode == 44 && caracter.indexOf(",") != -1) {
                return false;
            }
    
            //get the carat position
            var caratPos = getSelectionStart(el);
            var dotPos = el.value.indexOf(",");
            if (caratPos > dotPos && dotPos > -1 && (number[1].length > 1)) {
                return false;
            }
            return true;
        }
    
        function getSelectionStart(o) {
            if (o.createTextRange) {
                var r = document.selection.createRange().duplicate()
                r.moveEnd('character', o.value.length)
                if (r.text == '') return o.value.length
                return o.value.lastIndexOf(r.text)
            } else return o.selectionStart
        }
    
    </script>
    
查看更多
做个烂人
5楼-- · 2019-01-22 13:54

My problem was that I need it to show an error message in real time if the user is allowed only 2 decimals:

value = parseFloat(valueFromInput);
parseFloat(value.toFixed(2)) !== value // condition to check

The above code worked for me..toFixed converts the float to a string wit only 2 decimals and I have to convert back to float to check with the initial value if are the same.

P.S. And before this condition you should check if the value is NaN.

查看更多
▲ chillily
6楼-- · 2019-01-22 13:56
 function decimalValidation(el, evt) {
       var charCode = (evt.which) ? evt.which : event.keyCode;
       var number = el.value.split('.');
         if(charCode == 8) {
          return true;
         }
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        //just one dot
        if(number.length>1 && charCode == 46){
             return false;
        }
        //get the carat position
        var caratPos = getSelectionStart(el);
        var dotPos = el.value.indexOf(".");
        if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
            return false;
        }
        return true;
    }

function getSelectionStart(o) {
    return o.selectionStart
}

Hi @webvitaly The above code will work in IE too please check And backspace after decimals not working in Mozilla i updated my answer.

查看更多
7楼-- · 2019-01-22 14:01

You were almost there. Just check that there are no more than 2 characters after the decimal.

UPDATE 1 - check carat position to allow character insertion before the decimal.
UPDATE 2 - correct issue pointed out by ddlab's comment and only allow one dot.

 function validateFloatKeyPress(el, evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var number = el.value.split('.');
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    //just one dot (thanks ddlab)
    if(number.length>1 && charCode == 46){
         return false;
    }
    //get the carat position
    var caratPos = getSelectionStart(el);
    var dotPos = el.value.indexOf(".");
    if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
        return false;
    }
    return true;
}

//thanks: http://javascript.nwbox.com/cursor_position/
function getSelectionStart(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', o.value.length)
        if (r.text == '') return o.value.length
        return o.value.lastIndexOf(r.text)
    } else return o.selectionStart
}

http://jsfiddle.net/S9G8C/1/
http://jsfiddle.net/S9G8C/203/

查看更多
登录 后发表回答