Continuing from this (where an employee belongs_to role
and has a salary according to that role) I want to make my New Employee form
a bit more interactive: I want the salary
field's value to change according to the role
selected from the radio buttons group.
继续这个(员工在某个角色,并根据该角色拥有薪水)我想让我的新员工形式更具互动性:我希望薪资字段的值根据从单选按钮组中选择的角色进行更改。
My form now looks like this:
我的表单现在看起来像这样:
<%= simple_form_for(@room) do |f| %>
<%= f.input :name, label: 'Full Name', :required => true %>
<%= f.association :role, as: :radio_buttons, :required => true %>
<%= f.input :salary, label: 'Salary', :required => true %>
<%= f.button :submit %>
<% end %>
And my employees.js.coffee
file has this code:
我的employees.js.coffee文件有以下代码:
jQuery ->
$('#employee_employee_role_id_1').click ->
$(document.getElementById('employee_salary')).val(15)
where I have the values hardcoded to make sure there was no problem with my form fields ids.
我有硬编码的值,以确保我的表单字段ID没有问题。
What I need is to have the .click
method apply to all #employee_employee_role_id_X
fields (where X is the number of each radio button) and the value passed to .val() to be role.salary
我需要的是让.click方法适用于所有#employee_employee_role_id_X字段(其中X是每个单选按钮的编号),并将传递给.val()的值作为role.salary
But, as the newbie I am to both Rails and js/jQuery, I am clueless.
但是,作为Rails和js / jQuery的新手,我一无所知。
1 个解决方案
#1
0
Okay, I managed to make this work but I am not confident at all that this is the best way. Here goes:
好吧,我成功完成了这项工作,但我完全不相信这是最好的方法。开始:
In the form, I just added value_method: :salary
在表单中,我只添加了value_method :: salary
<%= f.association :role, as: :radio_buttons, value_method: :salary, :required => true %>
and in my .js.coffee
file:
在我的.js.coffee文件中:
jQuery ->
$("input[name='role[role_id]']").change ->
$(document.getElementById('salary')).val(($("input:radio[name='role[role_id]']:checked").val()))
Please feel free to comment or even provide a better answer if one exists! :)
如果存在,请随时发表评论,甚至提供更好的答案! :)
#1
0
Okay, I managed to make this work but I am not confident at all that this is the best way. Here goes:
好吧,我成功完成了这项工作,但我完全不相信这是最好的方法。开始:
In the form, I just added value_method: :salary
在表单中,我只添加了value_method :: salary
<%= f.association :role, as: :radio_buttons, value_method: :salary, :required => true %>
and in my .js.coffee
file:
在我的.js.coffee文件中:
jQuery ->
$("input[name='role[role_id]']").change ->
$(document.getElementById('salary')).val(($("input:radio[name='role[role_id]']:checked").val()))
Please feel free to comment or even provide a better answer if one exists! :)
如果存在,请随时发表评论,甚至提供更好的答案! :)