如何根据输入框商品名是否含led自动匹配对应税率计算
订单管理系统商品税率自动计算实现
核心规则落地说明:
- 商品名称包含
led关键词时适用12%税率,其余商品适用18%税率 - 匹配逻辑做大小写兼容,覆盖用户输入LED、Led、lEd等所有大小写变体场景,避免漏判
- 绑定输入框实时触发事件,用户输入商品名、价格后自动完成计算,无需额外操作
可直接运行的原生JS实现代码
<!-- 表单结构 --> <div class="order-input-group"> <div class="form-item"> <label>商品名称:</label> <input type="text" id="goodsName" placeholder="请输入完整商品名称"> </div> <div class="form-item"> <label>商品不含税单价(元):</label> <input type="number" id="goodsPrice" min="0" step="0.01" placeholder="请输入不含税价格"> </div> <div class="calc-result"> <p>匹配税率:<span id="showTaxRate">-</span></p> <p>应缴税费:<span id="showTax">-</span></p> <p>含税总价:<span id="showTotal">-</span></p> </div> </div> <script> // 绑定页面元素 const nameInput = document.getElementById('goodsName') const priceInput = document.getElementById('goodsPrice') const rateBox = document.getElementById('showTaxRate') const taxBox = document.getElementById('showTax') const totalBox = document.getElementById('showTotal') // 核心计算逻辑 function calcTaxFee() { const goodsName = nameInput.value.trim() const price = Number(priceInput.value) // 输入不合法时清空结果 if (!goodsName || !price || price < 0) { rateBox.textContent = '-' taxBox.textContent = '-' totalBox.textContent = '-' return } // 关键词匹配 const matchLed = goodsName.toLowerCase().includes('led') const currentRate = matchLed ? 0.12 : 0.18 // 数值计算 const tax = price * currentRate const total = price + tax // 渲染结果 rateBox.textContent = `${currentRate * 100}%` taxBox.textContent = `¥${tax.toFixed(2)}` totalBox.textContent = `¥${total.toFixed(2)}` } // 监听输入变化,实时计算 nameInput.addEventListener('input', calcTaxFee) priceInput.addEventListener('input', calcTaxFee) </script>
如果是在Vue、React等前端框架中使用,直接抽离核心判断逻辑即可:将输入的商品名称统一转为小写后判断是否包含
led关键词,匹配对应税率后完成税费计算。后续需要新增其他品类税率规则时,直接扩展关键词和税率的映射表即可,无需重构现有逻辑。
内容的提问来源于stack exchange,提问作者Feneel Patel
相关产品推荐
相关产品推荐

