简体   繁体   中英

Rails: How to create an array from checkboxes without a model and DB records?

I have a list of IDs and I want to create a form with a checkbox for each of them. If an ID is selected it should become part of an array. The array will be later used in a javascript, which is activated by a button.

Since I want to use only 1 button, the array should either update after each change in the checkboxes or the button should first submit the form of checkboxes and then calling the javascript which is using the submitted array from above.

Can I do all of this in a Rails view, and how, without using a model and DB records?

Use name of your array of check boxes with square brackets. For example, if you want it to be these_ids put something like this in your view, inside form_for block (here I just generate five check boxes, but in your case you should as you wish and all of them should have attribute name each with these_ids[] ):

...
<% [*1..5].each do |i| %>
 <%= check_box_tag 'these_ids[]', i %>
<% end %>
...

And when you submit form you will see in parameters:

Parameters: { ... "these_ids"=>["2", "5"] ... }

with those check boxes` ids that you were checked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM