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

如何从textarea、复选框及单选按钮取值并实现动态求和?

实时表单计算解决方案

问题

我需要从表单的所有字段(包括textarea、复选框、单选按钮)取值并计算总和,要求修改字段值或控件状态时,结果实时更新。以下是我目前的代码:

$(document).ready(function () {
  $("#orderbutton").on("click", function () {
    var weight = parseFloat($("#weight").val());
    var destination = $("#destination").val();
    var insurance = $("#chkbox1").val();

    //construct output
    var msg = "<div> Result Of your order: </div>";
    msg += "<div> Package weight: " + weight + " pounds </div>";
    if (weight <= 25) {
      msg += "<div> Base cost based on your weight: $15.00  <div>";
    } else if (weight <= 50) {
      msg += "<div> Base cost based on your weight: $25.00 <div>";
    } else {
      msg += "<div> Base cost based on your weight: $40.00 </div>";
    }
    if (destination == "ny") {
      msg += "<div> Destination Selected: New York State( No extra cost)</div>";
    } else {
      msg += "<div> Destination Selected: Out Of State ($15.00 Extra)</div>";
    }
    if ($("#chkbox1").is(":checked")) {
      msg += "<div>Insurance option: Insurance Choosen($10.00 Added)<div>";
    } else {
      msg += "<div> Insurance option: Insurance Not Choosen($0.00 Added)</div>";
    }
    msg += "<div> Total price of order: </div>";

    $("#output").html(msg);
  }); // end event handler
}); // end document.ready

实现思路与修改代码

核心要点

  1. 分离计算与渲染:把计算总价和生成结果HTML的逻辑拆成独立函数,方便多次调用
  2. 绑定实时触发事件:给所有表单控件绑定input/change事件,覆盖输入框输入、单选/复选框状态变化的场景
  3. 正确获取各类控件值:
    • 文本框/textarea:用parseFloat($(selector).val())转换为数字(空值时默认0,避免NaN错误)
    • 复选框:通过$(selector).is(':checked')判断是否选中,对应额外费用
    • 单选按钮:用$('input[name="radioName"]:checked').val()获取选中项的值

修改后的完整代码

$(document).ready(function () {
  // 定义计算并渲染结果的核心函数
  function calculateAndRender() {
    // 获取表单值
    const weight = parseFloat($("#weight").val()) || 0;
    const destination = $("#destination").val();
    const isInsuranceChecked = $("#chkbox1").is(":checked");

    // 计算各项费用
    let baseCost = 0;
    if (weight <= 25) baseCost = 15;
    else if (weight <= 50) baseCost = 25;
    else baseCost = 40;

    const destinationExtra = destination === "ny" ? 0 : 15;
    const insuranceCost = isInsuranceChecked ? 10 : 0;
    const totalCost = baseCost + destinationExtra + insuranceCost;

    // 生成结果HTML
    let msg = `<div>您的订单结果:</div>`;
    msg += `<div>包裹重量:${weight} 磅</div>`;
    msg += `<div>重量基础费用:$${baseCost.toFixed(2)}</div>`;
    msg += `<div>目的地:${destination === "ny" ? "纽约州(无额外费用)" : "州外(额外$15.00)"}</div>`;
    msg += `<div>保险选项:${isInsuranceChecked ? "已选择(额外$10.00)" : "未选择($0.00)"}</div>`;
    msg += `<div><strong>订单总价:$${totalCost.toFixed(2)}</strong></div>`;

    // 更新页面结果
    $("#output").html(msg);
  }

  // 绑定实时触发事件:输入框输入、下拉框/复选框变化
  $("#weight, #destination, #chkbox1").on("input change", calculateAndRender);

  // 页面加载完成后立即计算一次
  calculateAndRender();
});

说明

  • 实时更新:用户修改重量输入框、切换目的地下拉框、勾选/取消保险复选框时,结果会立即刷新
  • 异常处理:重量输入框为空时默认按0计算,避免出现非数字错误
  • 格式规范:用toFixed(2)确保金额统一显示两位小数
  • 代码复用:核心逻辑封装成函数,可在初始化、事件触发时重复调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:17:52