简体   繁体   English

如何通过Javascript更改输入[input = type]的值?

[英]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. 我还想分配键码来更改几个input[type=number]值,通过每次按-1 / + 1的增量来减去或增加值。 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 和我的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. 假设我要通过按=添加#whateverID1值,并通过按-减去#whateverID1值,请欣赏有关如何实现该目标的任何指南。 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; 
}

For one, using onclick/onkeydown things in html is usually bad practice. 首先,在HTML中使用onclick / onkeydown东西通常是不好的做法。 Rather, give the element an id or class and add an eventListener from the JS instead. 相反,给元素一个id或类,然后从JS添加一个eventListener。

Try this below, the jsfiddle is working and should let you do what you want: 请在下面尝试以下操作,jsfiddle正在运行,并且应该让您执行所需的操作:

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/ http://jsfiddle.net/Maxmaxs5/7thqo0zs/7/

If this helps or you need anything else, let me know! 如果这样做有帮助或您需要其他任何帮助,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM