allowing input only for float number

后端 未结 7 504
别那么骄傲
别那么骄傲 2020-12-09 21:58

I have pain-time when making input that only allows float number with jquery library. my code can\'t prevent chacacter \".\" when it\'s becoming first input, can anyone guid

相关标签:
7条回答
  • 2020-12-09 22:35

    Why not using Regular Expression

    ^[0-9]*[.][0-9]+$
    

    Read code and test here..

    0 讨论(0)
  • 2020-12-09 22:38

    Regular expression would be my recommendation as well. If the value is being passed as a number and not a string you can use .toString to change it to a string and validate it with regular expression. For example:

    var str = value.toString();
    if(!str.match(/^-?[0-9]*[.][0-9]+$/)) {
        alert("Value must be a float number");
        return;
    }
    return value;
    

    The above regex will match if the value passed is a floating point number. It accepts both negative and positive numbers. If you only want to accept positive numbers simply remove the '-?' from the expression. It will also fail if the value is simply zero '0' without any decimal point. If you want to accept zero simply add it as a condition to the 'if' statement.

    You can use the above validation and an onchange event to prevent the user from entering a non-flot number.

    0 讨论(0)
  • 2020-12-09 22:39

    Here is my solution, works with negative numbers too (fiddle)

    $("input").keypress(function (event) {
        var inputCode = event.which;
        var currentValue = $(this).val();
        if (inputCode > 0 && (inputCode < 48 || inputCode > 57)) {
            if (inputCode == 46) {
                if (getCursorPosition(this) == 0 && currentValue.charAt(0) == '-') return false;
                if (currentValue.match(/[.]/)) return false;
            } 
            else if (inputCode == 45) {
                if (currentValue.charAt(0) == '-') return false;
                if (getCursorPosition(this) != 0) return false;
            } 
            else if (inputCode == 8) return true;
            else return false;
    
        } 
        else if (inputCode > 0 && (inputCode >= 48 && inputCode <= 57)) {
            if (currentValue.charAt(0) == '-' && getCursorPosition(this) == 0) return false;
        }
    });
    function getCursorPosition(element) {
        if (element.selectionStart) return element.selectionStart;
        else if (document.selection)
        {
            element.focus();
            var r = document.selection.createRange();
            if (r == null) return 0;
    
            var re = element.createTextRange(),
                rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);
            return rc.text.length;
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-09 22:41

    I filter the first position input with the jQuery Caret plugin. Otherwise, once the dot is typed, it's already late to check where it was placed. I tried checking for the dot, then deleting the dot, but it does not look nice.

    jQuery caret plugin: http://examplet.buss.hk/js/jquery.caret.min.js

    What I did:

    http://jsfiddle.net/FCWrE/422/

    Try it :)

    $('.filterme').keypress(function(eve) {
      if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0)) {
        eve.preventDefault();
      }
    
      // this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
      $('.filterme').keyup(function(eve) {
        if ($(this).val().indexOf('.') == 0) {
          $(this).val($(this).val().substring(1));
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/caret/1.0.0/jquery.caret.min.js"></script>
    <input type="text" class="filterme">

    0 讨论(0)
  • 2020-12-09 22:41

    I use this - works for keyboard input or copy and paste

    $('input.float').on('input', function() {
      this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <input type="text" class="float" />

    Explanation:

    • First regex replaces anything that's not a number or a decimal.
    • Second regex removes any instance of a second decimal.
    0 讨论(0)
  • 2020-12-09 23:00

    You can use the following method, called on onkeypress event. Below is the HTML snippet followed by the JS method:

    input type="text" onkeypress="return isNumberKey(event)" id="floor"

    function isNumberKey(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode == 46){
            var inputValue = $("#floor").val();
            var count = (inputValue.match(/'.'/g) || []).length;
            if(count<1){
                if (inputValue.indexOf('.') < 1){
                    return true;
                }
                return false;
            }else{
                return false;
            }
        }
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)){
            return false;
        }
        return true;
    }
    

    Note: The above code also ensures that you enter only single decimal in the input.

    0 讨论(0)
提交回复
热议问题