How to update simple_form input field using AJAX?

I have a simple_form input field that is part of a form that I need to update asynchronously when the onchange event fires.

The field I need to update is displayed as a selection field, as it is a collection. But the collection represents entries of a nested dialing model. Therefore, when the user selects a specific value, I want to be able to update the same field with its children and provide the user with the option to select any of the children as a value for the same field.

The problem is, how can I update only this field without touching the rest of the form.

Just to give an idea of ​​my current setup: The form looks something like this:

 <%= simple_form_for @product, html: {class: 'form-horizontal'} do |f| %>
     <%= f.input :product_name %>
     <%= f.association :location, collection: @locations, input_html: { data: {remote: :true, url: "/update_locations"} } %>
 <%= f.submit 'Post', class: 'btn btn-default btn-lg' %>
  <% end %>
Run code

@product - , ~ strong > , @locations - , has_many , simple_form act_as_nested_set

. rb

get 'update_locations'    => 'products#update_locations'

:

  def update_locations
    @product = Product.new
    @location = Location.find_by_id(params[:product][:location_id])
    @locations = @location.children
    
    # TODO: render code that updates the simple_form field with
    # the new @locations collection
  end

, , .

+4
1

, , simple_form. AJAX , , HTML JS , HTML, JavaScript.

jQuery replaceWith .

, , .

JavaScript, AJAX. .html.erb, simple_form . JS jQuery replaceWith() , .

JS partial (location.js.erb):

var updatedLocations = $('#product_location_id', $('<%= j render "updateLocations" %>'))
$('#product_location_id').replaceWith(updatedLocations)

HTML erb partial (updateLocations.html.erb) :

<%= simple_form_for @product, html: {class: 'form-horizontal'} do |f| %>

<%= f.association :location, collection: @locations, input_html: { data: {update_locations: "true", remote: :true, url: "/update_locations"} } %>

<% end %>

:

  def update_locations
    @product = Product.new
    @location = Location.find_by_id(params[:product][:location_id])
    @locations = @location.children
    if @locations.empty?
      render nothing: true
    else
      render partial: 'locations'
    end
  end
+3

All Articles