使用基于前一个字段选择的数据填充rails表单
我有一个带有两个集合选择字段的表单。
我想根据第一个字段中选择的内容填充第二个字段中的数据。
#clientform = form_for(@booking, html: { class: "form-horizontal", role: "form" }) do |f| - if @booking.errors.any? .alert.alert-danger.alert-dismissable role="alert" button.close type="button" data-dismiss="alert" span aria-hidden="true" | × span.sr-only | Close h4= "#{pluralize(@booking.errors.count,"error")} prohibited this booking from being saved:" ul - @booking.errors.full_messages.each do |msg| li= msg #selectcourse .form-group = f.label :course = f.collection_select :course_id, Course.order(:title),:id,:title, {prompt: "Choose a course", include_blank: true}, {class: "form-control"} .form-group .col-sm-12 .next = link_to 'Next', '#', remote: true, class: "btn btn-primary" #selectdate .form-group = f.label :date = f.collection_select :date, dates, :to_s, :to_s, include_blank: false .form-group .col-sm-12 .next = link_to 'Next', '#', remote: true, class: "btn btn-primary" .form-group.hidden .col-sm-offset-2.col-sm-10 = f.submit class: "btn btn-primary"
选择第一个字段后,用户单击下一个触发ajax调用
$('.next').click -> console.log 'next' $.ajax url: '/bookings/course_availability' type: 'POST' dataType: 'json' contentType: 'application/json' data: JSON.stringify({course: $("#booking_course_id").val();}) success: (data) -> console.log 'success' return return
控制器返回一个@dates对象,一个包含不同日期的数组,但我不知道如何使用这些数据填充表单…
我想根据第一个字段中选择的内容填充第二个字段中的数据
通常称为动态选择框以供将来参考。
–
如果您正在收到@dates
对象,您将能够使用以下内容:
$(document).on "click", ".next", -> $.ajax url: '/bookings/course_availability' type: 'POST' dataType: 'json' contentType: 'application/json' data: JSON.stringify({course: $("#booking_course_id").val();}) success: (data) -> $dropdown = $("select#date") $dropdown.empty() $.each JSON.parse(data), (index, value) -> $dropdown.append ''
非常古老的skool; 你基本上覆盖了第二个select
选项列表。 这将立即在DOM中更新。
–
一些好的参考:
- Railscasts动态选择菜单
- Rails 4动态选择菜单
第一:
您不必使用NEXT
按钮进行ajax调用,也可以在第一个(Course)选择中监听on-change
事件。
现在回答你的问题:
当ajax调用返回@dates
响应时(你说是一个不同日期的数组),你现在可以通过迭代这个数组,将@dates
响应中的这些日期数组绑定到第二个选择的选项的值,并且根据这个SO答案 ,建立要附加的标签。
或者,你可以使用JQuery selectable
库,它带有用于rails的JQuery-UI gem ,这个function就像Andrey Koleshko的rails-guide中所解释的那样。 。