Format number in an HTML5 input tag

后端 未结 3 1515
星月不相逢
星月不相逢 2021-01-18 17:00

This is my input


Is it possible to only allow users to enter

相关标签:
3条回答
  • 2021-01-18 17:21

    function inputLimiter(e,allow) {
        var AllowableCharacters = '';
    
        if (allow == 'custom'){AllowableCharacters=' 1234567890.';}
    
    
        var k = document.all?parseInt(e.keyCode): parseInt(e.which);
        if (k!=13 && k!=8 && k!=0){
            if ((e.ctrlKey==false) && (e.altKey==false)) {
            return (AllowableCharacters.indexOf(String.fromCharCode(k))!=-1);
            } else {
            return true;
            }
        } else {
            return true;
        }
        
        }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="NameCharacters" onkeypress="return inputLimiter(event,'custom')" value="" maxlength="4" /></p>

    In Javascript. But this was as far as I got, will just leave this here for awhile, need to handle other stuffs.

    0 讨论(0)
  • 2021-01-18 17:34

    It can be achieved using javascript with corner case handling using toLocaleString()

    function getChange(){
      // 48 - 57 (0-9)
      var str1 = valueRef.value;
      if((str1[str1.length-1]).charCodeAt() < 48 || (str1[str1.length-1]).charCodeAt() > 57){
        valueRef.value = str1.substring(0,str1.length-1 );
        return;
      } 
    
     // t.replace(/,/g,'')
      let str = (valueRef.value).replace(/,/g,'');
    
      let value = +str;
    
      valueRef.value = value.toLocaleString();
    }
    

    Working Codepen Demo Link

    0 讨论(0)
  • 2021-01-18 17:35

    I think you can try something like this:

    input type="number" name="number" pattern="([0-9]{1,3}).([0-9]{1,3})" title="Must contain a decimal number">
    

    see here

    Added Plunkr: Plunker

    0 讨论(0)
提交回复
热议问题