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

如何让自定义数字输入框支持负数输入?

How to Add Negative Number Support to Your Custom jQuery Numeric Input

To allow negative numbers in your custom input, we need to make two key changes: let users type the minus sign (only at the start of the input) and adjust the validation logic to handle negative values correctly. Here's the modified code with explanations:

Modified Full Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="edt" type="text" placeholder="Number">

<script>
$(document).ready(function() { 
    // Example: Allow values from -100 to 100 (adjust min/max as needed)
    addNumericOnlyEvent($("#edt"), -100, 100); 
}); 

function addNumericOnlyEvent(element, minValue, maxValue) { 
    element.on('input', function(e) { 
        const val = element.val();
        let currentValue = Number(val);

        // Allow standalone minus sign so users can finish typing negative numbers
        if (val === '-') {
            return;
        }

        // Reset to minValue if input is not a valid number
        if (isNaN(currentValue)) {
            element.val(minValue);
            return;
        }

        // Clamp value between min and max (works for negative min values)
        if (currentValue < minValue) {
            element.val(minValue);
        } else if (currentValue > maxValue) {
            element.val(maxValue);
        }
    }); 

    element.keydown(function(e) { 
        // Allow minus sign only at the start of the input
        if ((e.keyCode === 189 || e.keyCode === 109)) {
            const inputVal = element.val();
            // Block minus if it already exists or cursor isn't at the beginning
            if (inputVal.startsWith('-') || element[0].selectionStart !== 0) {
                e.preventDefault();
            } else {
                return; // Let the minus be typed
            }
        }

        // Keep existing allowed keys (backspace, delete, tab, shortcuts, arrow keys, decimal)
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || 
            (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) || 
            (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) || 
            (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) || 
            (e.keyCode >= 35 && e.keyCode <= 39)) { 
            return; 
        } 

        // Block non-numeric keys (excluding the minus we already handled)
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { 
            e.preventDefault(); 
        } 
    }); 
}
</script>

Key Changes Explained

  1. Allow Minus Sign in Keydown Handler:

    • We added checks for the minus key codes (189 for keyboard hyphen, 109 for numpad minus).
    • The minus is only allowed if:
      • The input doesn't already start with a minus, and
      • The cursor is positioned at the very start of the input. This prevents users from adding minus signs in the middle of positive numbers.
  2. Adjust Input Validation:

    • We now handle the case where the input is just a standalone minus sign (val === '-'), letting users keep it so they can type the rest of the negative number instead of immediately resetting to minValue.
    • The clamping logic works seamlessly with negative minValue values (e.g., if you set minValue: -100, it will correctly limit inputs to that minimum).
  3. Update Initialization:

    • When calling addNumericOnlyEvent, set your minValue to a negative number if you want to allow negative inputs (like -100 in the example).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:06:04