Counting a check_box selections?

Hello to everybody!

I have the following code in new.html.erb allowing a user to
select more questions (item) for creating a questionnaire:


<% for item in @itemss %>
<%= check_box_tag “questionnaire[item_ids][]”, item.id,
@questionnaire.items.include?(item) %>
<%= item.kind %> <%= item.question %>
- “<%= item.denomination %>” - p.ti <%= item.score %>

<% end %>

I would like to show, while the user is making his choices, the
calculation of:

  • the number of selected items
  • the sum of the scores (each item has its own score)

any suggestions?

use jquery and bind click event to some calculcation function. you can
set some value or metadata to count with

eg

= check_box_tag ‘name’, value, checked?, :‘data-count’ => 123, :class =>
‘sums’

and you jquery

var result; // global variable

jQuery(‘.sums’).each(function() {
jQuery(this).bind(‘click’, function() {
result+= parseInt(jQuery(this).attr(‘data-count’)) *
(jQuery(this).attr(‘checked’)) ? 1 : -1;
});
});

in data-count you can have the value you want to inc/dec from final
result
when user clicks, jquery will evaluate checked state, when checked,
it’ll increase the result, when unchecked, it’ll decrease

tom

On Jul 24, 2011, at 20:15 , mr ma wrote:

     - "<%=  item.denomination %>" - p.ti <%= item.score %> <br/>


Posted via http://www.ruby-forum.com/.


You received this message because you are subscribed to the Google G. “Ruby
on Rails: Talk” group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.

Tomas Meinlschmidt, MS {MCT, MCP+I, MCSE, AER}, NetApp Filer/NetCache

www.meinlschmidt.com www.maxwellrender.cz www.lightgems.cz

Thank you very much Tomas!!!
I have not yet used jquery, I will study it a little bit…
Marco

Hi Tomas,

I studied a little Javascript and I write this script but
the variable ‘result’ is undefined, can you help me? :wink:

=> new.html.erb

<% @itemss.each do |item| %> <%= check_box_tag "questionnaire[item_ids][]", item.id, @questionnaire.items.include?(item), :'data-count' => item.score, :class => 'sums', :onClick => "calculate();" %> <%= item.kind %> <%= item.question %> - "<%= item.denomination %>" - p.ti <%= item.score %>
<% end %>

...

=> application.html.erb