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

如何用JavaScript/jQuery设置三个数字输入框的总和最大值为50

实现三个数字输入框总和不超过50的方案

这问题我之前也碰到过,核心思路就是实时监控输入框的变化,动态调整数值,确保三个输入框的总和始终不超过50。下面给你两种实现方案,原生JavaScript和jQuery的都有:

原生JavaScript实现

这种方案不需要依赖任何库,直接用浏览器原生API就能实现:

// 获取所有name以"cat"开头的输入框
const catInputs = document.querySelectorAll('input[name^="cat"]');

// 定义处理输入变化的逻辑函数
function handleInputChange(e) {
    // 把所有输入框的值转成数字,空值/非数字默认按0处理
    const inputValues = Array.from(catInputs).map(input => Number(input.value) || 0);
    // 计算当前总和
    const total = inputValues.reduce((sum, val) => sum + val, 0);

    // 如果总和超过50,调整当前输入框的值
    if (total > 50) {
        // 计算另外两个输入框的总和
        const otherInputsTotal = total - Number(e.target.value);
        // 把当前输入框的值设为「50 - 另外两个的总和」,同时确保不低于0(符合输入框min属性)
        e.target.value = Math.max(0, 50 - otherInputsTotal);
    }
}

// 给每个输入框绑定input事件(覆盖输入、粘贴等操作)
catInputs.forEach(input => {
    input.addEventListener('input', handleInputChange);
});

说明

  • 用querySelectorAll批量选中目标输入框,避免重复获取元素
  • 处理了空值和非数字的情况,确保计算不会出错
  • 只调整当前正在输入的那个框的数值,用户体验更友好
  • 保证数值不会低于输入框的min="0"限制

jQuery实现

如果你的项目已经引入了jQuery,可以用更简洁的语法实现:

// 给目标输入框绑定input事件
$('input[name^="cat"]').on('input', function() {
    // 获取所有输入框的数值,空值/非数字按0处理
    const inputValues = $('input[name^="cat"]').map(function() {
        return Number($(this).val()) || 0;
    }).get();
    // 计算总和
    const total = inputValues.reduce((sum, val) => sum + val, 0);

    if (total > 50) {
        // 计算当前输入框应调整到的数值
        const otherInputsTotal = total - Number($(this).val());
        $(this).val(Math.max(0, 50 - otherInputsTotal));
    }
});

说明

  • 核心逻辑和原生JS完全一致,只是用jQuery的选择器和事件绑定简化了代码
  • map().get()是jQuery特有的写法,用来把集合转成普通数组
  • 同样处理了边界情况,确保数值合法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:37:33