简体   繁体   中英

Populate rails form with data based on the previous field select

I have a form with two collection select fields.

I want to populate the data in the second field depending on what is selected in the first field.

#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"

after the first field is selected a user clicks next which triggers an ajax call

$('.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

the controller returns a @dates object, an array containing different dates but I don't know how to populate the form with this data...

First:

Instead of using a NEXT button to make the ajax call, you can as well just listen for an on-change event on the first(Course) select.

Now to answer your question:

When the ajax call returns the @dates response, (which you said is an array of different dates), you can now bind these dates array in @dates response to the value of the options of the second select by iterating on this array, and building <option>...</option> tags to be appended, according to this SO answer.

Alternatively, you can use the JQuery selectable library, which comes with the JQuery-UI gem for rails, for this functionality as explained in this rails-guide by Andrey Koleshko. .

I want to populate the data in the second field depending on what is selected in the first field

Often called dynamic select boxes for future reference.

--

If you're receiving the @dates object back, you'll be able to use the following:

$(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>'

Very old-skool; you're basically overwriting the second select options list. This will update in the DOM immediately.

--

Some good refs:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM