How to make an input only accept numbers Binary input type="text" name="number" / [closed]

-1

How do I make this field accept only binary numbers that do not accept 12 or 13 and etc., just numbers 1 and 0, such as 0000111 or 1000 or 11111 ??

    
asked by anonymous 13.10.2018 / 22:36

1 answer

1

function SomenteNumero(e){
 var tecla=(window.event)?event.keyCode:e.which;
if((tecla==48 || tecla==49)) return true;
 else{
return false;
 }
 }
<input type="text" size="10" value=""' onkeypress="return SomenteNumero(event);">
  • A function is a JavaScript procedure - an instruction set that executes a task or calculates a value. To use a function, you must define it somewhere in the scope of which you want to call it.
  • The onkeypress event occurs when the user presses a key (on the keyboard) - in this case, calls the function.
  • keyCode (Keyboard Codes): Represents the key number that the user presses on the keyboard 48 is zero and 49 is the one.
  • If (if) the key is zero or one, fine, accept (return true)
  • else (else) does not accept.
  

I noticed that keyCode is now obsolete and will be discarded:

I tested with e.key

function SomenteNumero(e){
 var tecla=(window.event)?e.key:e.which;
if((tecla==48 || tecla==49)) return true;
 else{
return false;
 }
 }
<input type="text" size="70" value=""' onkeypress="return SomenteNumero(event);">

in modern browsers.

    
13.10.2018 / 23:08