If type 0 to 9 then set text and a to z also set text

https://jsfiddle.net/2xsnawdk/

 $(".writehere1").on('keydown', function() {
   var key = event.which || event.key;
   if (key < '0' || key > '9') {
     $('#test1').html('detect if write number').fadeIn(500, 'linear');
   }
 });

 $(".writehere2").on('keydown', function() {
   var key = event.which || event.key;
   if (key < 'a' || key > 'z') {
     $('#test2').html('detect if write letter').fadeIn(500, 'linear');
   }
 });

So my problem with if not really understand at all. On first input if write a-z to 0-9 works both why? On second input detect nothing?

So want to detect if write only from letters in other cases show nothing and also with numbers.

Thanks!

Can you show an example of what the user might type and explain what you want to see?

If you write in first input 0 to 9 then show a text with .html function otherwise show nothing. And same with a to z.

Thanks!

 $(".writehere1").on('keydown', function() {
   var key = event.which || event.key;
   if (key < '0' || key > '9') {
     $('#test1').html('detect if write number').fadeIn(500, 'linear');
   }
 });

You are comparing a number (key) to a string ‘0’, ‘9’. You also should console.log the value of key. I think you might be surprised at the value when entering any number 0-9.

So you think because string?

 $(".writehere1").on('keydown', function() {
   var key = event.which || event.key;
   if (key < 0 || key > 9) {
     $('#test1').html('detect if write number key ' +key).fadeIn(500, 'linear');
   }
 });

https://jsfiddle.net/bxw2j01y/

So remove string but still why show message if still write only letters not numbers?

Thanks!

Put a console.log(key) before the if statement and see what the value of key is for every number 0-9. Then type in any letter and see what key is. Then you will see the problem.

1 Like

I plan to event key:

event.key 0 to event.key 9 not like 48 and 57? So cant use this for that detect purpose? As it use event.which?

48

event.key

0

event.location

0(General keys)

event.which[(deprecated)](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent)

48

event.code

Digit0

57

event.key

9

event.location

0(General keys)

event.which[(deprecated)](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent)

57

event.code

Digit9

Thanks!