如何在Rails表单输入时实时将变量传递给CoffeeScript函数
实现Rails表单输入实时传递变量到CoffeeScript
我来帮你搞定这个实时传递变量的需求,咱们一步步来优化和实现:
第一步:修正视图里的HTML规范问题
首先你视图里有个小问题:多个元素用了同一个id="questions",这不符合HTML的id唯一性规范,我先把这部分改成class,同时调整form_tag的语法细节,让代码更严谨:
<%= form_tag('/welcome/how_much', method: :post, remote: true) do %> <div class="question-group"> <h5 class="label">Estimated new home cost?</h5> <%= text_field(:amount, id: "house_amount", placeholder: "ex. 100,000", class: "form-control form-control-lg") %> </div> <div class="question-group"> <h5 class="label">Estimated payment for a new home?</h5> <%= text_field(:high_rent, id: "high_rent", placeholder: "ex. 1,200", class: "form-control form-control-lg") %> </div> <div class="question-group"> <h5 class="label">Current Monthly Rent?</h5> <%= text_field(:current_rent, id: "current_rent", placeholder: "ex. 800", class: "form-control form-control-lg") %> </div> <%= submit_tag("See how quickly you can buy a home", data: { toggle: "modal", target: "#savings_modal" }, class: "btn btn-success btn-lg") %> <!-- Modal for sign-up --> <div class="modal" id="savings_modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <h3 class="modal-title" id="savingsModalTitle">You could be ready to buy in <%= @months_to_buy %> months</h3> <h5 class="modal-title">and have <%= @total_savings %>* to put towards a down payment & a drastically increased credit score using LikeHome</h5> <div class="modal-body"> <h4>Sign-up Now to get started!</h4> <%= render '_tenant_signup_modal_form.html.erb' %> </div> </div> </div> </div> <% end %>
第二步:编写CoffeeScript实时监听逻辑
接下来在对应的CoffeeScript文件(比如app/assets/javascripts/welcome.coffee)里,监听输入框的实时输入事件,把三个输入框的值传递给你的自定义函数:
# 监听三个输入框的实时输入(用户每打一个字符就触发) $(document).on 'input', '#house_amount, #high_rent, #current_rent', -> # 获取输入值,同时去掉逗号(方便后续数字计算) houseAmount = $('#house_amount').val()?.replace(/,/g, '') || '' highRent = $('#high_rent').val()?.replace(/,/g, '') || '' currentRent = $('#current_rent').val()?.replace(/,/g, '') || '' # 调用你的业务逻辑函数,传递三个变量 updateSavingsCalculation houseAmount, highRent, currentRent # 示例自定义函数,你可以在这里写自己的业务逻辑 updateSavingsCalculation = (houseCost, estimatedPayment, currentRent) -> # 比如先打印到控制台调试 console.log "Home Cost: #{houseCost}, Estimated Payment: #{estimatedPayment}, Current Rent: #{currentRent}" # 如果需要实时更新页面元素(比如模态框预览),可以在这里操作 # 示例: # if houseCost && estimatedPayment && currentRent # estimatedMonths = calculateMonths(houseCost, estimatedPayment, currentRent) # $('#savingsModalTitle').text("You could be ready to buy in #{estimatedMonths} months")
额外优化:模态框弹出前的校验/处理
因为你用了Bootstrap模态框,还可以监听模态框即将显示的事件,在弹出前做最后一次值的校验或计算:
# 监听模态框即将显示的事件 $(document).on 'show.bs.modal', '#savings_modal', -> houseAmount = $('#house_amount').val()?.replace(/,/g, '') || '' highRent = $('#high_rent').val()?.replace(/,/g, '') || '' currentRent = $('#current_rent').val()?.replace(/,/g, '') || '' # 校验是否所有字段都已填写 if !houseAmount || !highRent || !currentRent alert "Please fill in all three fields to see your savings estimate!" # 阻止模态框弹出 return false
可选:处理异步表单提交结果
因为你的表单是remote: true,如果后端会返回计算结果,可以监听异步提交成功事件来更新模态框内容:
# 监听表单异步提交成功事件 $(document).on 'ajax:success', 'form[action="/welcome/how_much"]', (event, responseData) -> # 用后端返回的数据更新模态框 $('#savingsModalTitle').text("You could be ready to buy in #{responseData.months_to_buy} months") $('.modal-title:eq(1)').text("and have #{responseData.total_savings}* to put towards a down payment...")
这样就能实现用户输入时实时把三个变量传递给CoffeeScript函数,同时兼顾表单提交和模态框的交互逻辑啦!
内容的提问来源于stack exchange,提问作者SupremeA
相关产品推荐
相关产品推荐

