How to make an input accept only Binary numbers <input type="text" name="number"/>

Asked

Viewed 199 times

-1

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

  • Guy no good now he’s only accepting either 0 or 1. like a binary number 11001 HE DOESN’T ACCEPT!! PLEASE SOMEONE CAN HELP ME?

  • https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

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 - a set of instructions that executes a task or calculates a value. To use a function, you must define it somewhere in the scope 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 number of the key the user presses on the keyboard 48 is the zero and 49 is the one.
  • If (if) the key is zero or one, all right, it accepts (Return true)
  • else (IS) does not accept.

I noticed that the 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.

  • thank you very much it worked!! now if it’s not too much you could explain the code to me.. my main focus is to learn...

  • (window.Event)? Event.keycode:e. which is the part I’m missing. what is this WINDOW.EVENT there by what I understand, if it is true it goes to EVENT.KEYCODE if it is not it goes to the :e. which; woe would like to know what these are and why there in INPUT passed as parameter the word EVENT. thank you if you can explain to me as you said, learning is my focus and I will be very grateful if you help me understand better

  • Some browsers keep the key in event.which and others in event.keycode, and Qualcuno is just making sure to grab the value, whatever the browser. Another alternative would be tecla = e.which || e.keyCode. If the pressed keys are "0" or "1" the function returns true, which means: "go ahead!". If it is not "0" or "1" returns false, which means "abort the event".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.