开发者

How can I get all the checked items from a submitted form with sinatra's params?

I'm running Sinatra 1.0 with HAML, my form has a number of checkboxes, for example books I like, and you would select all the books you want. The checkbox name is "books".

In sinatra params['books'] th开发者_开发百科ere should be an array of all the books that were checked, but it only has the last item that was checked, not an array.

How can I get all the checked items?

HAML:

%form{:action => "/test", :method => 'post'}
  %input{:name=>'check',:type=>'checkbox',:value=>'item1'} item 1
  %input{:name=>'check',:type=>'checkbox',:value=>'item2'} item 2
  %input{:name=>'check',:type=>'checkbox',:value=>'item3'} item 3
  %input{:type => "submit", :value => "send", :class => "button"}

Sinatra get method

post '/test' do
  puts params['check'] #should be an array but is last item checked
end


Very close, but do not but numbers in the arrays

%form{:action => "/test", :method => 'post'}
    %input{:name=>'check[]',:type=>'checkbox',:value=>'item1'} item 1
    %input{:name=>'check[]',:type=>'checkbox',:value=>'item2'} item 2
    %input{:name=>'check[]',:type=>'checkbox',:value=>'item3'} item 3

Now,

post '/test' do  
  puts params['check'] #puts an array of what was checked to stdout
end


Wouldn't that output a bunch of checkboxes with the same name? If so, params['check'] is probably getting replaced with each new checkbox.

Try naming each one something different. If you really want it in an array, try hacking the names:

%input{:name=>'check[1]',:type=>'checkbox',:value=>'item1'} item 1
%input{:name=>'check[2]',:type=>'checkbox',:value=>'item2'} item 2
%input{:name=>'check[3]',:type=>'checkbox',:value=>'item3'} item 3


Try


%input{:type => "checkbox", :value => "1", :name => "checkbox[]", :id => "id1"} Chk1
%input{:type => "checkbox", :value => "2", :name => "checkbox[]", :id => "id2"} Chk2
%input{:type => "checkbox", :value => "3", :name => "checkbox[]", :id => "id3"} Chk3

Then in the rails or sinatra


puts params[:checkbox]

Then you can see the checked items.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜