Andy Chin
Andy Chin

Reputation: 19

How to change value of input[type=number] on key press via Javascript?

I already have a series of events of keypress to trigger some sound, to run countdown clock and whatnot.

I also want to assign keycode to change the value of a couple of input[type=number], either subtract or add value by incremental of -1/+1 each key press. I have done some search but couldn't really give me the ultimate guide.

Here's what I have in the header.

function runScript(e){
if(e.keyCode == 32 && e.shiftKey){
   gameclock();
}}

and on my html

<body onkeydown="runScript(event)"> 
...
<input id="whateverID1" type="number" value="00">

Let's say if I want to add #whateverID1 value by pressing = and subtract #whateverID1 value by pressing -, appreciate any guide to how can I achieve that. Thank you very much.

I have tried this but doesn't seem to work.

var CounterName = 0; 
if(e.keyCode == 49 ) {
document.getElementById('whateverID1').value = ++CounterName;
} 
if(e.keyCode == 50 ) { 
document.getElementById('whateverID1').value = --CounterName; 
}

Upvotes: 1

Views: 1734

Answers (1)

Kieran McWilliams
Kieran McWilliams

Reputation: 101

For one, using onclick/onkeydown things in html is usually bad practice. Rather, give the element an id or class and add an eventListener from the JS instead.

Try this below, the jsfiddle is working and should let you do what you want:

document.getElementById("bodyId").addEventListener("keydown", function (event) {
  var CounterName = 1;
  var currentValue = parseInt(document.getElementById('whateverID1').value);

  if(event.keyCode == 187) {
    document.getElementById('whateverID1').value = currentValue + CounterName;
  }
  else if(event.keyCode == 189) { 
    document.getElementById('whateverID1').value = currentValue - CounterName;
  }
});

http://jsfiddle.net/Maxmaxs5/7thqo0zs/7/

If this helps or you need anything else, let me know!

Upvotes: 2

Related Questions