You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript中如何仅允许Tab、退格键和数字键?附keypress事件代码

Solution to Allow Tab, Backspace, and Numeric Keys in JavaScript

Hey there! Let's tweak your existing function to let Tab and Backspace keys work while keeping the numeric input and length restrictions you already have.

Your current code blocks all non-numeric keys—including Tab (critical for navigating between form fields) and Backspace (essential for deleting characters), which aren't great for user experience. Here's the fixed version:

Modified Function Code

function isNumberKey(evt, el) {
  // Get the correct key code (handles cross-browser differences)
  var charCode = evt.which ? evt.which : evt.keyCode;

  // Allow Tab (keyCode 9) and Backspace (keyCode 8) to pass through
  if (charCode === 8 || charCode === 9) {
    return true;
  }

  // Keep the existing numeric key check (only 0-9 allowed)
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }

  // Maintain the input length limit (max 3 characters total)
  if (el.value.length > 2) {
    return false;
  }

  return true;
}

Key Changes Breakdown

  • Tab & Backspace Exception: We added a check for these two keys first—if either is pressed, we immediately return true to let the action happen.
  • Consistent Event Handling: Updated event.keyCode to evt.keyCode to use the passed event parameter consistently, avoiding potential global event issues.
  • Preserved Original Rules: The numeric key restriction and 3-character length limit stay exactly as you had them.

Full Usage Example

<input type="text" onkeypress="return isNumberKey(event, this)" placeholder="Enter up to 3 digits">

Quick Test Checklist

  • Press Tab: You should be able to navigate away from the input normally.
  • Press Backspace: You can delete existing characters without issues.
  • Type numbers: Only 0-9 are allowed, and you can't enter more than 3 digits.
  • Try letters/symbols: These will be blocked as expected.

内容的提问来源于stack exchange,提问作者NOUFAL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:20:03