RoR结合Stimulus.js实现输入数值累加显示NaN问题求助
Stimulus 数值相加功能修复方案
存在的问题点
- 读取输入框内容时未获取
value属性:直接将DOM元素对象传入数值转换方法,转换结果必然为NaN - 数值转换方法不匹配业务场景:你需要处理decimal/货币类型的带小数数值,使用
parseInt会直接丢弃小数部分,应该改用parseFloat - 无异常输入兼容逻辑:输入框为空、用户输入非数字内容时,数值转换会得到NaN,相加后总费用依然显示NaN
- 触发事件不符合实时更新要求:当前仅绑定了
change事件,只有输入框失焦时才会触发计算,需要新增input事件实现输入过程中实时更新
修复后控制器代码(cost_calculate.controller.js)
import { Controller } from 'stimulus' export default class extends Controller { static targets = [ 'landCost', 'profServices', 'totalCost' ] updateTotalCost () { const totalCost = this.landCost() + this.profServices() this.totalCostTarget.value = totalCost.toFixed(2) } landCost () { return parseFloat(this.landCostTarget.value) || 0 } profServices () { return parseFloat(this.profServicesTarget.value) || 0 } }
说明:多余的totalCost方法没有用到可以直接删除,|| 0逻辑会在输入为空、输入非数字时默认返回0,避免出现NaN。
修复后表单代码
<%= simple_form_for @project, html: { "data-controller" => "cost-calculate" }, url: wizard_path(step, project_id: @project.id) do |f| %> <%= f.text_field :land_cost, data: { target: 'cost-calculate.landCost', action: "input->cost-calculate#updateTotalCost change->cost-calculate#updateTotalCost" }, class: "project-dropdown-width" %> <%= f.text_field :prof_services, data: { target: 'cost-calculate.profServices', action: "input->cost-calculate#updateTotalCost change->cost-calculate#updateTotalCost" }, class: "project-dropdown-width" %> <%= f.text_field :total_cost, data: { target: 'cost-calculate.totalCost' }, label: false, class: "project-dropdown-width" %> <% end %>
说明:同时绑定input和change事件,既保证输入时实时计算,也兼容用户通过 autofill、右键粘贴等操作触发的数值变更。
内容的提问来源于stack exchange,提问作者DaveC
相关产品推荐
相关产品推荐

