简体   繁体   中英

Allow typing only float percentage value for input

I followed this link to allow type only float percentage value for input. Here is original jsfiddle.

I tried to replace regular expression and use this /^((0|[1-9]\\d?)(\\.\\d{1,2})?|100(\\.00?)?)$/ or this ^([1-9]([0-9])?|0)(\\.[0-9]{1,2})?$ , but it doesn't work.

edit// In my case only float number between 0 and 100 is allowed

jsfiddle

var pastValue, pastSelectionStart, pastSelectionEnd;

$("input").on("keydown", function() {
    pastValue          = this.value;
    pastSelectionStart = this.selectionStart;
    pastSelectionEnd   = this.selectionEnd;
}).on("input propertychange", function() {
    var regex = /^((0|[1-9]\d?)(\.\d{1,2})?|100(\.00?)?)$/;

    if (this.value.length > 0 && !regex.test(this.value)) {
        this.value          = pastValue;
        this.selectionStart = pastSelectionStart;
        this.selectionEnd   = pastSelectionEnd;
    }
});

The problem with your re is that the decimal part requires the full stop AND the digit at the same time. That's hard to type ;)

Try /^(100(\\.0{0,2})?|(\\d|[1-9]\\d)(\\.\\d{0,2})?)$/ . That'll allow the . without digits.

Edit: Changed re to not allow 100 with decimals above .00.

Regards

I use this functions to allow only numeric values or number, with max 2 decimal

You'll need to give the inputs a data-type="numeric" or data-type="decimal"

You could also use HTML5's <input type="number" />

$(function() {
    // allow only numbers
    var ctrlAltShift = false;
    $(document).keydown(function(e) {
        if (e.keyCode >= 16 && e.keyCode <= 18 ) ctrlAltShift = true;
    }).keyup(function(e) {
        if (e.keyCode >= 16 && e.keyCode <= 18 ) ctrlAltShift = false;
    });
    $("[data-type=numeric]").keydown( function(e) {
        if( 
            (
                !ctrlAltShift && (
                    ( e.keyCode >= 48 && e.keyCode <= 57 ) ||
                    ( e.keyCode >= 96 && e.keyCode <= 105 ) ||
                    ( $.inArray(e.keyCode, [8, 9, 27, 35, 36, 37, 39, 46]) !== -1 )
                ) 
            ) ||
                ctrlAltShift && e.keyCode == 9 
        ) {
            return;
        }
        else {
            e.preventDefault();
        }        
    });


    // allow only numbers with 2 decimals
    $("[data-type=decimal]").keydown( function(e) {
        if(
            (
                !ctrlAltShift && (
                    ( e.keyCode >= 48 && e.keyCode <= 57 ) ||
                    ( e.keyCode >= 96 && e.keyCode <= 105 ) ||
                    ( $.inArray(e.keyCode, [8, 9, 27, 35, 36, 37, 39, 46, 110, 190, 194]) !== -1 )
                )
            ) ||
                ctrlAltShift && e.keyCode == 9 
        ) {
            if( $.inArray(e.keyCode, [110, 190, 194]) !== -1 ) {
                e.preventDefault();
                if( $(this).val().length != 0 && $(this).val().indexOf('.') == -1 ) {
                    $(this).val( $(this).val() + '.');
                }
            }
        }
        else {
            e.preventDefault();
        }
    }).keyup(function(e) {
        var value = $(this).val();

        if( value.indexOf('.') != -1) { 
            if( value.split(".")[1].length > 2 ) {
                var newValue = parseFloat( Math.floor(value * 100) / 100).toFixed(2);
                e.preventDefault();
                $(this).val( newValue );
            }
        }        
    });
});

It surely can be optimized to one function.

DEMO:

 $(function() { // allow only numbers var ctrlAltShift = false; $(document).keydown(function(e) { if (e.keyCode >= 16 && e.keyCode <= 18 ) ctrlAltShift = true; }).keyup(function(e) { if (e.keyCode >= 16 && e.keyCode <= 18 ) ctrlAltShift = false; }); $("[data-type=numeric]").keydown( function(e) { if( ( !ctrlAltShift && ( ( e.keyCode >= 48 && e.keyCode <= 57 ) || ( e.keyCode >= 96 && e.keyCode <= 105 ) || ( $.inArray(e.keyCode, [8, 9, 27, 35, 36, 37, 39, 46]) !== -1 ) ) ) || ctrlAltShift && e.keyCode == 9 ) { return; } else { e.preventDefault(); } }); // allow only numbers with 2 decimals $("[data-type=decimal]").keydown( function(e) { if( ( !ctrlAltShift && ( ( e.keyCode >= 48 && e.keyCode <= 57 ) || ( e.keyCode >= 96 && e.keyCode <= 105 ) || ( $.inArray(e.keyCode, [8, 9, 27, 35, 36, 37, 39, 46, 110, 190, 194]) !== -1 ) ) ) || ctrlAltShift && e.keyCode == 9 ) { if( $.inArray(e.keyCode, [110, 190, 194]) !== -1 ) { e.preventDefault(); if( $(this).val().length != 0 && $(this).val().indexOf('.') == -1 ) { $(this).val( $(this).val() + '.'); } } } else { e.preventDefault(); } }).keyup(function(e) { var value = $(this).val(); if( value.indexOf('.') != -1) { if( value.split(".")[1].length > 2 ) { var newValue = parseFloat( Math.floor(value * 100) / 100).toFixed(2); e.preventDefault(); $(this).val( newValue ); } } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Numeric: <input type="text" data-type="numeric" /><br /> Decimal: <input type="text" data-type="decimal" /> 

@SamWhan 的响应几乎是正确的,它并不完全正确,因为它接受100.100.0类的值,要修复它,请将 regEx 更改为

/^(100|(\d|[1-9]\d)(\.\d{0,2})?)$/

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