【问题标题】:Update textfield using a selectbox in ruby on rails使用 ruby​​ on rails 中的选择框更新文本字段
【发布时间】:2022-01-27 18:45:25
【问题描述】:

我是 Rails 新手,我在下面有一个表单,我需要使用选择框中选择的选项(调整价格)更新文本字段(汽车价格)。下拉需要有多个百分比选项,如 100% 、 50% 和 25% 。 when one percentage is selected then it should update the car price in the field with new calculated adjusted price.

<% car =  Car.find(params[:id]) %>

<table class="part" width="100%">
  <tr style="vertical-align: top;">
    <td><b>Car Model</b></td>
    <td><b>Price</b></td>
    <td><b>Adjusted price</b></td>
 </tr>

<tr style="vertical-align: top;">
  <td><%= text_field(‘Car’, ‘car_name’, size: 10, value: check_for_car_name(car.name)) %></td>
  <td><%= text_field(‘Car’, ‘price’, size: 10, value: check_for_car_price(car.price)) %></td>
  <td><%= select(adjusted price(not sure of this part)) %></td>
</tr>

</table>

我不确定如何即时更新汽车价格的选择框?提前致谢。

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby ruby-on-rails-5


    【解决方案1】:

    看看rails guides,你可以使用options_for_select结合select_tag

    <%= select_tag(:city_id, options_for_select([["25%", 1], ["50%", 2]])) %> 
    

    这将输出

    <option value="1">25%</option>
    <option value="2">50%</option>
    

    现在,要动态更新价格,您可能需要在前端使用 javascript,例如在您的选择中添加 event listener。 Then, when selected option is for example 50% you can do calculations directly on the price field by changing it's value.

    document.getElementById('price').value = calculated price
    

    或者由于问题被标记为 jQuery,您可以使用 .val()

    $("#price").val() = calculated price
    

    【讨论】:

    • 嗨@Marelons,感谢您的回答。对于百分比计算,我需要在辅助类中编写一个单独的 ruby​​ 方法吗?或者可以使用 javascript 来完成?您可以将事件列表器添加到选择中吗?谢谢。
    • 百分比计算应该像将价格乘以 0.25 等一样简单。事件侦听器:获取您的选择 select = document.getElementById('cars'),然后您可以添加 console.logs 结果的回调。 select.addEventListener('change', (event) =&gt; {console.log(event.target.value)}) 现在,您可以使用event.target.value 将其保存到变量中,对其进行修改并将其作为字段值插入。
    猜你喜欢
    • 1970-01-01
    • 2011-04-01
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 2011-05-18
    • 2012-12-19
    相关资源
    最近更新 更多