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

如何用jQuery启用输入框编辑并联动更新年度总访问量

问题修复:允许手动编辑房间数并联动计算年度总访问量

当前代码的核心问题是:任何输入框的变化都会强制重置numrooms的值为numshops/5,导致用户手动修改的房间数会被立刻覆盖,无法保留。我们需要调整逻辑,让numrooms仅在numshops变化时自动更新,同时支持手动修改numrooms并联动计算结果。

修改后的代码

JavaScript 代码

// 初始计算:设置numrooms的默认值
let numShopsVal = parseInt(jQuery("#numshops").val()) || 0;
jQuery("#numrooms").val(numShopsVal / 5);

// 监听输入事件
jQuery('#numofapples, #numshops, #numrooms, #avgcustomer').on('input', function() {
    // 只有当修改的是numshops时,才自动更新numrooms
    if (this.id === 'numshops') {
        let numShopsVal = parseInt(jQuery(this).val()) || 0;
        jQuery("#numrooms").val(numShopsVal / 5);
    }

    // 获取各输入框的当前值(处理空值,避免NaN)
    let numApples = parseInt(jQuery("#numofapples").val()) || 0;
    let avgCustomer = parseInt(jQuery("#avgcustomer").val()) || 0;
    let numRooms = parseInt(jQuery("#numrooms").val()) || 0;

    // 计算年度总访问量
    let totalAnnualVisits = numApples * avgCustomer * numRooms;
    jQuery("#totalvisitperyear").val(totalAnnualVisits);
});

HTML 代码(无需修改,保留原结构)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form id="" action="" method="post">
  <div class="form-right">
    <table width="100%">
      <tr>
        <td width="60%" valign="top">
          <label> 1. 您拥有多少个苹果? <br/>
                      <input name="" id="numofapples" placeholder="" type="number" required />
                    </label>
          <label> 2. 您拥有多少家店铺?<br/>
                      <input name="" id="numshops" type="number" value="10" placeholder="" required />
                    </label>
          <label> 3. 每家店铺平均房间数<br/>
                      <input name="" id="numrooms" type="number" value="" placeholder="" required />
                    </label>
          <label> 4. 每家店铺日均客流量 <br/>
                      <input name="" id="avgcustomer" type="number" placeholder="" required />
                    </label>

        </td>
        <td width="40%" valign="top">
          <p>年度总访问量 </p>
          <input value="" type="text" name="" id="totalvisitperyear" />

        </td>
      </tr>
    </table>

  </div>

</form>

关键调整说明

  • 区分触发源:通过this.id === 'numshops'判断,只有修改店铺数量时才自动更新房间数,手动修改房间数时不会被覆盖。
  • 空值处理:使用|| 0确保输入为空时不会出现NaN的计算结果。
  • 直接使用房间数当前值:计算总访问量时,直接读取numrooms的用户输入值,而非依赖店铺数量的计算值,满足手动编辑的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:08:20