Creating and passing an array from a form to a controller using jquery

I have a form (form_for), and I want the user to be able to select multiple "categories" using the select method.

= form_for @place, :url=>{:action=>"#"} do |f| #appended_wrapper .categories = f.label :categories, "Categories: " = f.select :categories, %w(Active Art Auto Food), {:include_blank => true} = f.submit "Submit" 

Every time a user selects a category, I have jQuery, add a div with the category value so that users can see and delete the categories that they added.

 $('#hotel_categories').change(function(){ value = $(this).val(); $('#appended_wrapper').append( '<div class="appended"> '+value+' <a class="remove" href="#">Remove</a></div>' ); $('.remove').click(function(){ $(this).parent(".appended").remove(); }); }); 

When I click the submit button, I want all the selected categories to be passed to my controller in an array.

How do I achieve this?

Thanks.

+4
source share
1 answer

Inside your div, add a hidden input field like this:

 <input name="category_ids[]" type="hidden" value="1"> 

The value represents the category identifier. Note the square brackets next to category_ids. All hidden inputs must have the same name.

Values ​​will be passed as an array in the params hash in your controller.

+3
source

Source: https://habr.com/ru/post/1439045/


All Articles