javascript input allowing only numbers

2020-07-23 06:22发布

i use this code and it works

<HTML>
  <HEAD>
    <SCRIPT language=Javascript>
       <!--
       function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : event.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       }
       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
           type="text" name="txtChar">
  </BODY>
</HTML>

but I do not have access to the html, and have only javascript

document.getElementById("txtChar").addEventListener("keypress", <<your code>>, false);

what should be in place <<your code>>?

p.s. found another bug with this component:
when you copy-paste(ctrl-v or right click-paste) it does not work
can someone know how to resolve it

标签: javascript
7条回答
三岁会撩人
2楼-- · 2020-07-23 06:32

I know I'm a little late to the party.

The HTML5 example by jAndy is probably the best answer for browsers that support it. The JavaScript answer by Josaph was good as well in that it inspired my answer to solve the questioner's addendum and my problem.

The following throws away input that matches the regex (not a digit, replace with an empty string), and is invoked anytime there's input, even from a paste.

 function stripNonNumeric() {
   this.value = this.value.replace(/\D+/g, '');
 }

 var txtChar = document.getElementById("txtChar");
 if (txtChar.addEventListener) {
   txtChar.addEventListener("input", stripNonNumeric);
 } else if (txtChar.attachEvent) {
   txtChar.attachEvent("oninput", stripNonNumeric);
 }

I'm not a JavaScript guy, I'm not sure if this is a good way to solve the problem, or if there are performance issues to consider. However, it works for me.

查看更多
Fickle 薄情
3楼-- · 2020-07-23 06:40

Try this code bro. i hope it will help you a lot i use jQUERY.

<head>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>


<input id="txtChar" type="text" name="txtChar">

</body>


<script>

    $("#txtChar").keypress(function(e) {
       var charCode = (e.which) ? e.which : event.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
    });

</script>
查看更多
劫难
4楼-- · 2020-07-23 06:41

It's a mistake?

document.getElementById(**"txtChar"**).addEventListener("keypress", function(){
                return isNumberKey(event);
            }, false);
查看更多
狗以群分
5楼-- · 2020-07-23 06:42

If you can't go with HTML5 <input type="number"> then I would regex the input value allowing only numbers. I modified a script I wrote to accomplish a similar task. It allows pasting and strips any non-integer character.

var arrowKeys = [37, 38, 39, 40];  

function stripChars( e ) {
  // Don't execute anything if the user is just moving the cursor around and
  // not really entering anything new.
  if(arrowKeys.indexOf(e.keyCode) !== -1){ return; }

  var elem = e.currentTarget,
      cursorPos = elem.selectionEnd;

  // strip any unwanted character and assign the value back
  elem.value =  elem.value.replace(/\D/g,'');
  // this avoids the cursor shifting to the end of the input 
  // when inserting an integer in the middle of an already existing number
  elem.selectionEnd = cursorPos;
  elem.focus();
}

var elem = document.getElementById('elem');

elem.addEventListener('keyup', stripChars, false); 
elem.addEventListener('paste', stripChars, false); 

Anyway, you can view the original script with tests here and a demo of the above code here.

查看更多
神经病院院长
6楼-- · 2020-07-23 06:45

event is unknown inside function. So mention the event object to function:

document.getElementById("myElement").addEventListener("keypress", function(event){ return isNumberKey(event); }, false);

EDIT: The question changed a bit, so quoting the answer:
1. Change "myElement" to "txtChar"
2. include event object as parameter

document.getElementById("txtChar").addEventListener("keypress", function(event){
                    return isNumberKey(event);
                }, false);
查看更多
做自己的国王
7楼-- · 2020-07-23 06:46

In <<your code>> add the name of the function to handle it, isNumberKey in this case; and also you need to add evt.preventDefault(); before return false;

This function below only accepts codes corresponding to digits from 0 to 9 and ignores dots ("."), hyphens ("-") and minus signs ("−").

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 46 || charCode > 31 && (charCode < 48 || charCode > 57)){
        evt.preventDefault();
        return false;
    }
    return true;
}

Configure the input field for HTML5 browsers:

txtChar = document.getElementById("txtChar")
txtChar.addEventListener("keypress", isNumberKey, false);

//Attributes
txtChar.type = "number";
txtChar.min = 0;
txtChar.pattern = "\\d+";
txtChar.placeholder = "Only integer positive numbers";
txtChar.required = "required";

Working example including styling from jAndy's answer: http://jsfiddle.net/pL9Zk/

查看更多
登录 后发表回答