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

如何根据Select选中项动态设置Number输入框的最大值?

解决方案

不需要用foreach循环,直接监听下拉框的选择变化事件,根据选中的选项设置数字输入框的最大值即可,具体实现如下:

调整后的HTML(给元素加ID方便获取)

<select name="select" id="itemSelect">
   <option value="item-one">Item one</option>
   <option value="item-two">Item two</option>
</select>

<input type="number" name="quantity" id="quantityInput">

JavaScript 实现

// 获取DOM元素
const itemSelect = document.getElementById('itemSelect');
const quantityInput = document.getElementById('quantityInput');

// 初始化设置默认选中项对应的最大值
updateMaxQuantity(itemSelect.value);

// 监听下拉框变化事件
itemSelect.addEventListener('change', function() {
  updateMaxQuantity(this.value);
});

// 根据选中项设置最大值的函数
function updateMaxQuantity(selectedValue) {
  if (selectedValue === 'item-one') {
    quantityInput.max = 3;
  } else if (selectedValue === 'item-two') {
    quantityInput.max = 4;
  }
}

说明

  • 给两个元素添加ID,方便快速获取DOM节点
  • 初始化时先设置当前选中项对应的最大值,避免页面加载时输入框没有限制
  • 通过change事件监听下拉框的选择变化,每次切换时调用函数更新输入框的max属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:42:34