简体   繁体   中英

allowing input only for float number

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 guide me to solve this problem?

$('.filterme').keypress(function(eve) {
   if (    ( eve.which != 46 || $(this).val().indexOf('.') != -1 ) 
        && ( eve.which <  48 || eve.which > 57 ) 
        || ( $(this).val().indexOf('.') == 0) 
      )
   {
       eve.preventDefault();
   }
});​

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.

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">

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.

Why not using Regular Expression

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

Read code and test here..

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.

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;
}

This works for me:

var str = document.getElementById('product_'+id_product).value;
if( !str.match(/^[0-9]*([.,][0-9]+)?$/) ) {
 console.log("Value must be a number or float number");
}else{
 console.log("The number is valid");
}

I hope this can help someone. Regards!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM