开发者

Allow only numeric input in a text input, and allow a hyphen as an optional first character

开发者 https://www.devze.com 2023-02-02 01:53 出处:网络
I need to automatically clean user entry into a text input - to only allow numbers, except for the first character, which could be a number or a hyphen.

I need to automatically clean user entry into a text input - to only allow numbers, except for the first character, which could be a number or a hyphen.

So, for example, if the user types 138a29 it would be automatically updated to 13829.

I was using an onKeyPress event to check the keyCode to allow only numbers, but that's proved to be a little difficult to truly allow only numbers without breaking arrow keys, backspace keys, etc in so开发者_运维问答me browsers. And now there is a new requirement to allow a hyphen(-) as an optional first character, but a hyphen is not valid anywhere else in the string.

I have the Prototype library to use for my particular project, but no jQuery.


The simplest way to do this is to avoid the keyCode and use the textbox's value on keyup. Something like this...

Event.observe('myInput', 'keyup', function(){
    var value = this.value, first;
    if(value.length == 0)
         return;

    first = value.charAt(0);
    value = value.replace(/[^0-9]/g,'');

    if(first == '-')
        value = first + value;

    this.value = value;
    return true;
});


Try this

<script type="text/javascript">
function whatKey(e) {
    var thetext = document.getElementById('tt');   // Current value
    var theKey = String.fromCharCode(e.keyCode);   // key entered
    var combval = thetext.value + theKey;          // Result would be this

    return (!isNaN(combval) || combval=='-');      // if result OK, accept key

}
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消