Allowing only numbers and one decimal

后端 未结 6 1939
醉梦人生
醉梦人生 2020-12-19 17:58

Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i\'m having is that when i tab over to my textbox contro

6条回答
  •  忘掉有多难
    2020-12-19 19:01

    If you can't use an already stable and well-know library, you can try something like this:

    document.write('');
    
    function run(field) {
        setTimeout(function() {
            var regex = /\d*\.?\d?/g;
            field.value = regex.exec(field.value);
        }, 0);
    }
    

    I know it doesn't prevent the wrong char to appear, but it works.

    PS: that setTimeout(..., 0) is a trick to execute the function after the value of the field has already been modified.

提交回复
热议问题