Search code examples
javascriptruby-on-railssimple-form

How to pass <li> elements to form in ruby on rails


Currently in my ruby on rails project, my events/new.html.erb looks like this:

<h2>Neuer Event</h2><br>
<div id="kalendi">
  <%= render 'kalendi' %>
</div>

<ul class="lista">

</ul>


<%= simple_form_for(@event) do |f| %>
    <%= f.input :name %>
    <%= f.input :content %>
    <%= f.input :date%>
    <%= f.input :tag_list, as: :check_boxes, collection: ['Logik', 'Ethik', 'Metaphysik'] %><br>
    <%= f.button :submit %>
<% end %>

<script>
  $(document).ready(function(){
    $(document).on('click', ".btn2", function () {
      var buttonContent = $(this).html();
      $(".lista").append("<li>" + buttonContent + "</li>");
    });
  });
</script>

The div "kalendi" generates a calendar, where the user can pick out some dates. Let's say, the user has chosen "2016-02-08", "2016-02-09" and "2016-02-10". The <ul class="lista"> looks like this:

<ul class="lista">
 <li>2016-02-08</li>
 <li>2016-02-09</li>
 <li>2016-02-10</li>
</ul>

I want that, when the user presses the submit-button, that the input of <%= f.input :date%> is an array of the chosen dates. What do I need to do? Thanks in advance!

Edit: I heard, that it isn't easy to pass an array from the simple_form gem to the controller. Let's change my question a bit: What do I need to do, so the controller gets a string like this: "2016-02-08, 2016-02-09, 2016-02-10"?

Edit 2, trying to follow the advice of Albert Paul: I added a hidden field like this:

<%= simple_form_for([@event, @dateevent]) do |f| %>
    <%= f.input :date, :as => :hidden, :input_html => { :value => ".alist" } %>
    <%= f.button :submit %>
<% end %>

And just for testing, I created a div called alist:

<div class="alist">abcdefghijklmnopqrstuvwxxxxz</div>

At the moment, the value of date is ".alist". What do I need to type in XXX { :value => "XXX" }, to get the content of the div? I tried something like this:$(".alist").val(), but it didn't work. Thanks in advance!

Edit3: Nevermind, I found a solution.


Solution

  • Rails would only pickup input tags as params, but we can do a hack and get those elements by using Javascript. Add a hidden field to your form, and add a click event to your submit button, when user submit your page use jquery to copy contents of <li></li> to this hidden field, so when it gets submitted you'll get your values inside your hidden field.

    hidden_field(:signup, :pass_confirm)
    

    http://apidock.com/rails/ActionView/Helpers/FormHelper/hidden_field

    Use jquery text() to get contents of <li>

    http://api.jquery.com/text/

    Not the preferred way to do this, I recommend using rails checkbox tag.