D
D
Dubolom Unicellular2020-05-04 21:17:55
JavaScript
Dubolom Unicellular, 2020-05-04 21:17:55

How to optimize this code?

I have something like "custom textarea" i.e. when you click on the button (I did so far only when you click on the numbers) of the keyboard, the button that I clicked should be displayed in the span:

$(document).on("keydown", e => {
  switch(e.keyCode) {
    case 48:
      $("span").append("0");
      break;
    case 49:
      $("span").append("1");
      break;
    case 50:
      $("span").append("2");
      break;
    case 51:
      $("span").append("3");
      break;
    case 52:
      $("span").append("4");
      break;
    case 53:
      $("span").append("5");
      break;
    case 54:
      $("span").append("6");
      break;
    case 55:
      $("span").append("7");
      break;
    case 56:
      $("span").append("8");
      break;
    case 57:
      $("span").append("9");
      break;
  }
});

How to optimize this mess?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
twobomb, 2020-05-04
@duboloms

$(document).on("keydown", e => {
  if(e.key.search(/\d/) != -1)
      $("span").append(e.key);
});

I
Ivan, 2020-05-04
@youmixx

I don't know much about JS, but that's basically it.

$(document).on("keydown", e => {
  for(i = 48; i < 58; i++)
  {
    if(e.keyCode == i)
    {
      $("span").append(i-48);
    }
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question