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

jQuery实现多选select下拉框联动控制数字输入框显隐技术咨询

实现方案

1. 调整原有HTML+PHP代码

首先将原有三个文本输入框修改为number类型,默认全部隐藏:

<div class="form-group">
  <label for="unit_of">Unit of Measure</label>
  <select class="form-control-sm selectpicker" multiple="multiple" id="unit_of" name="unit_of[]" data-selected-text-format="count">
  <?php 
    $sql = "select * from unit_of";
    $res = mysqli_query($db_handle, $sql);
    while ($list = mysqli_fetch_assoc($res)) {
      $unit_of = $list['unit_of'];
  ?>
    <option value="<?= $unit_of ?>"><?= $unit_of; ?></option>
  <?php } ?>
  </select>
</div>
<!-- 三个输入框默认全部隐藏,统一改为number类型 -->
<input type="number" class="form-control-sm rate-input" id="rates" name="" style="display:none">
<input type="number" class="form-control-sm rate-input" id="rates1" name="" style="display:none">
<input type="number" class="form-control-sm rate-input" id="rates2" name="" style="display:none">

注意:给option补充了value属性,避免取值异常。

2. 添加JS交互逻辑

因为你使用了selectpicker(Bootstrap多选组件),直接绑定对应change事件即可实现需求:

// 预先定义每个选项对应的输入框配置
const unitConfig = {
  'Per Minute': { name: 'per_minute', placeholder: 'Enter Rate Per Minute' },
  'Per Page': { name: 'per_page', placeholder: 'Enter Rate Per Page' },
  'Per Hour': { name: 'per_hour', placeholder: 'Enter Rate Per Hour' },
  'Per Day': { name: 'per_day', placeholder: 'Enter Rate Per Day' },
  'Per Month': { name: 'per_month', placeholder: 'Enter Rate Per Month' },
  'Per Item': { name: 'per_item', placeholder: 'Enter Rate Per Item' },
  'Per Contract': { name: 'per_contract', placeholder: 'Enter Rate Per Contract' },
  'Others': { name: 'others', placeholder: 'Enter Other Rate' }
}
const $rateInputs = $('.rate-input');

// 监听多选框变更事件,兼容selectpicker组件
$('#unit_of').on('changed.bs.select', function() {
  // 获取当前选中的所有选项值
  const selectedUnits = $(this).val() || [];
  // 先重置所有输入框:隐藏、清空内容、重置属性
  $rateInputs.hide().val('').attr('name', '').attr('placeholder', '');
  
  // 最多取前3个选中项,依次对应三个输入框
  selectedUnits.slice(0, 3).forEach((unit, index) => {
    const config = unitConfig[unit];
    if (!config) return;
    const $input = $rateInputs.eq(index);
    $input.attr('name', config.name).attr('placeholder', config.placeholder).show();
  })
})

逻辑说明

  • 提前建立所有可选选项和输入框属性的映射关系,后续新增选项只需在unitConfig里补充配置即可
  • 每次多选框变更时先重置所有输入框,再按选中顺序给前3个输入框赋值对应配置并显示
  • 输入框改为number类型自带数值校验,符合业务场景需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:15:03