0

In my view I am iterating through a collection of Customers called @colleagues and displaying them in a list as checkbox inputs like so:

<ol>
  <% @colleagues.each do |c|%>
    <li>
       <input type="checkbox">
           <%= c.full_name %>
           <%= c.id %>
       </input>
    </li>
  <% end %>
</ol>

What I wish to do is collect each checked/selected name in an array, which, on pushing of a button, will be sent to my controller. My question is, how can I create a dynamic array in javascript so that a colleague's id is added to the array or removed when unchecked?

Thanks

3
  • You can do it without JS, but using Rails form. Will it work for you? Or you insist us to give you JS solution ? let me know, then I can probably help you Commented Feb 2, 2016 at 10:52
  • FYI, input is void element, your HTML markup as no meaning. Now to send checkboxes to server, set value and name attribute and serialize them (or serializeArray)or use a form to wrap them Commented Feb 2, 2016 at 10:55
  • @ArupRakshit I think I need to use JS because I need to use AJAX to send info back and forth between the controller without losing the view, as it's not sent to the controller on form submit Commented Feb 2, 2016 at 10:57

1 Answer 1

2

Maybe this example can help you:

<ul id="featuresOptions" class="options" style="display: block;">
    <li><label><input type="checkbox" name="Apartment" value="6"> Apartment</label></li>
    <li><label><input type="checkbox" name="House" value="7"> House</label></li>
    <li><label><input type="checkbox" name="Lot" value="8"> Lot</label></li>
    <li><button class="button" id="featuresButton">Filter</button></li>
</ul>

$(document).on('click', "#featuresButton", function() {
    var formData = [];
    $("#featuresOptions li input").each(function(e) {
        if($(this).is(":checked")) {
            formData.push($(this).val());
        }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

this is quite useful thank you. The line $(this).val(); is retrieving the value specified within the input tags, but the value I want is the id, is there a way I can set an input's value to be the @colleague's id?
Yes like <input type="checkbox" value="<%= c.id %>"><%= c.full_name %></input> BTW if you are sticking with my answer, please tick it as ;)
brilliant, I can't believe I couldn't think of that myself! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.