Jquery通过向上/向下箭头键盘增加/减少输入文本中的数字

Jquery increase/decrease number in input text by up/down arrows keyboard

本文关键字:输入 文本 数字 增加 Jquery 键盘      更新时间:2023-09-26

>我有一个基本的数量字段,并希望允许用户根据键盘向上/向下增加/减少此输入框中的数字。

以下自: 濒危马萨 键盘代码上的答案 https://stackoverflow.com/a/375426/560287 如何将它添加到键控函数中?

var keynum = 0;
if(window.event) { keynum = e.keyCode; }  // IE (sucks)
else if(e.which) { keynum = e.which; }    // Netscape/Firefox/Opera
if(keynum == 38) { // up
    //Move selection up
}
if(keynum == 27) { // down
    //Move selection down
}
//cache our input since we will be working with it each time an arrow key is pressed
var $input = $('input');
//bind the the `keydown` event for the `document` object which will catch all `keydown` events that bubble up the DOM
$(document).on('keydown', function (event) {
    //up-arrow (regular and num-pad)
    if (event.which == 38 || event.which == 104) {
        //make sure to use `parseInt()` so you can numerically add to the value rather than concocting a longer string
        $input.val((parseInt($input.val()) + 1));
    //down-arrow (regular and num-pad)
    } else if (event.which == 40 || event.which == 98) {
        $input.val((parseInt($input.val()) - 1));
    }
});

这是一个演示:http://jsfiddle.net/QRNP8/1/

请注意,jQuery 将 charCode/keyCode 属性规范化为 event.which

查询规范化跨浏览器的以下属性 一致性:

target
relatedTarget
pageX
pageY
which
metaKey

来源: http://api.jquery.com/category/events/event-object/

将输入类型设置为数字也可以。虽然这在IE9及更低版本中不会太好。

<input type="number">

来源: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_input_number

有一个小的jQuery插件可以做到这一点:https://github.com/nakupanda/number-updown

用法:

$('#textInput').updown();

在此处观看现场演示: http://jsfiddle.net/XCtaH/embedded/result/

支持的键盘和鼠标滚轮事件

$("input").keypress(function(event) {
      var val=$(this).val();
      if ( event.keyCode== 38) {
          val++
         $(this).val(val)
      }
      if ( event.keyCode== 40) {
          val--
          $(this).val(val)
      };    
});

你可以做:

<input type="text" id="yourinput" value="0">
$(document).on("keypress", '*', function(e) {
    if (e.keyCode == 38) { // up
        $('#yourinput').val(parseInt($('#yourinput').val(), 10) + 1);
    }
    if (e.keyCode == 40) { // down
        $('#yourinput').val(parseInt($('#yourinput').val(), 10) + 1);
    }
});

在这里摆弄 http://jsfiddle.net/mSCBL/1/

$("something").keyup(function(e){
    var keynum = 0;
    if(window.event) { keynum = e.keyCode; }  // IE (sucks)
    else if(e.which) { keynum = e.which; }    // Netscape/Firefox/Opera
    if(keynum == 38) { // up
       //Move selection up
    }
    if(keynum == 27) { // down
       //Move selection down
    }
});

其中something是与您的输入匹配的选择器。

你的代码看起来是正确的。如果您只是想知道如何将代码绑定到事件...

$('#itemId').keyup(function(e){ 
    /*YOUR CODE*/  
});

这应该有效

if(keynum == 38) { // up
    this.value = parseInt(this.value)-1;
}
if(keynum == 27) { // down
    this.value = parseInt(this.value)+1;
}