0

How can I have a collection_select with 5 options to chose from and when either one is chosen it cannot be picked again for the next (i.e. if 1 is picked first then only 2,3,4,5 are available to pick from).

I have two tables: invoices and Invoice_Line_Items , invoice has_many Invoice_Line_items. Invoice_Line_Items belongs_to Invoice. The options are relations. For instance, I cannot invoice twice for the same item.

<%= collection_select( :invoice_line_item, :invoice_line_item_id, @invoice_line_items, :id, :supplier_id, {}, {:multiple => true}) %>

Thank you

davefogo
  • 93
  • 1
  • 9
  • It really depends on your models and what the options are, are they relations or actual values? Add some more details or example code to make this question answerable. – max Apr 15 '15 at 08:50
  • Edit the question and add the details... please – max Apr 15 '15 at 09:01

1 Answers1

1

You'll need some javascript for this. The example below is based on just two dropdowns, with the value of the first being removed from the list of options in the second once it's chosen, but you should be able to adapt this for the amount you require. Note the "collect_2.remove(collect_1.value - 1)" part - this is because the count of the drop-down objects begin at 0, but their value begins at 1 - a little confusing!

<!DOCTYPE html>
<html>
<body>

<%= form_tag("/users", method: "get", name:"frm") do %>  
    <%= collection_select(:invoice_line_item, :invoice_line_item_id, @invoice_line_items, :id, :supplier_id, {},{onchange: "myFunction()",id:"collect-1", multiple: true }) %><br>
    <%= collection_select(:invoice_line_item, :invoice_line_item_id, @invoice_line_items, :id, :supplier_id, {},{id:"collect-2", multiple: true}) %><br>   
  <%= submit_tag("Go") %>
<% end %>

<script>
function myFunction() {  
    var collect_1 = document.getElementById("collect-1");
    var collect_2 = document.getElementById("collect-2"); 
    collect_2.innerHTML = collect_1.innerHTML;
    collect_2.remove(collect_1.value - 1);    
}   
</script>

</body>
  • In which file should I add the code? Sorry its the first time I see javascript in rails. Would it be inside the form? – davefogo Apr 15 '15 at 15:06
  • Yes, all of the above is inside the form file. It can be separated, and some people prefer to do that, but in this example since the javascript code will probably be completely unique to that form, I would just keep it in the same file. – FunTimeFreddie Apr 16 '15 at 04:14