簡體   English   中英

根據前一個字段選擇的數據填充Rails表單

[英]Populate rails form with data based on the previous field select

我有一個帶有兩個集合選擇字段的表單。

我想根據在第一個字段中選擇的內容來填充第二個字段中的數據。

#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對象,一個包含不同日期的數組,但是我不知道如何用此數據填充表單...

第一:

除了使用NEXT按鈕進行ajax調用外,您還可以只在第一個(課程)選擇上監聽on-change事件。

現在回答您的問題:

當ajax調用返回@dates響應(您說是不同日期的數組)時,現在可以通過在此數組上進行迭代,將@dates響應中的這些date數組綁定到第二個select的選項的值,然后根據此SO答案 ,構建要附加的<option>...</option>標簽

另外,您可以使用JQuery selectable庫,該庫隨Rails的JQuery-UI gem一起提供, 如Andrey Koleshko的rails指南中所說明的那樣。

我想根據第一個字段中選擇的內容填充第二個字段中的數據

通常稱為動態選擇框,以供將來參考。

-

如果您收到@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 '<option>' + value + '</option>'

很老套 您基本上是在覆蓋第二個select選項列表。 這將立即在DOM中更新。

-

一些不錯的參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM