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) %>
          <a> <%= item.kind %> <span> <%= item.question %> </span> </a>
          - "<%= item.denomination %>" - p.ti <%= item.score %> <br/>
     <% 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

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

=> application.html.erb
...
  <script language="javascript" type="text/javascript">
  function calculate() {
      var sezione = document.getElementById('scores');
      var result;
      n_item = jQuery("input:checkbox:checked").length;

      jQuery('.sums').each(function() {
        jQuery(this).bind('click', function() {
          result+= parseInt(jQuery(this).attr('data-count')) *
          (jQuery(this).attr('checked')) ? 1 : -1;
        });
      });
      sezione.innerHTML = "N. Item selezionati: " +n_item +" Tot. punti:
" +result;
  }
  </script>