Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - Limit number of characters in input type number

Im trying to limit to X number the characters in a input (type of number). ive tried a lot of options and none seems to work. I dont want to use the option tel as it needs the numeric keyboard on a mobile device (yes, with ., and all the symbols) I tried also the pattern solution but it only worked for iOS, didnt work in android (displayed the normal keyboard).

The best way would be that if the user hits the limit dont let him type anymore, if he wants to highlight the text and re-type a different number he is allow to. Just not let him type more than the specified number of characters.

So, any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: charCode is non-standard and deprecated, whereas keyCode is simply deprecated.

Check this code

JavaScript

<script>
function check(e,value)
{
    //Check Charater
    var unicode=e.charCode? e.charCode : e.keyCode;
    if (value.indexOf(".") != -1)if( unicode == 46 )return false;
    if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
}
function checkLength()
{
    var fieldLength = document.getElementById('txtF').value.length;
    //Suppose u want 4 number of character
    if(fieldLength <= 4){
        return true;
    }
    else
    {
        var str = document.getElementById('txtF').value;
        str = str.substring(0, str.length - 1);
        document.getElementById('txtF').value = str;
    }
}

and HTML input with number type below

onInput //Is fired also if value change from the side arrows of field in Chrome browser

<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />

Fiddle Demo

Update -- Little bit generic code example

Change above function into this one

function checkLength(len,ele){
  var fieldLength = ele.value.length;
  if(fieldLength <= len){
    return true;
  }
  else
  {
    var str = ele.value;
    str = str.substring(0, str.length - 1);
    ele.value = str;
  }
}

In HTML use like this

<!-- length 4 -->    
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength(4,this)" />
<!-- length 5 -->    
<input  type="number" onKeyPress="return check(event,value)" onInput="checkLength(5,this)" />
<!-- length 2 -->    
<input  type="number" onKeyPress="return check(event,value)" onInput="checkLength(2,this)" />

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...