0

I want to make a select all checkbox based on this findle. I made a coffeescript like this:

$(document).on 'click','.select_all_clans', ->
  if $(this).is(':checked')
    $('.clan_checkbox').attr 'checked', true

But it works only when the check_box.clan_checkbox was not selected earlier, and it checks them only once.

This is my form:

<%= form_tag show_schools_path do %>
 <p>
   Wybierz klan/y: 
   Feniks: <%= check_box_tag 'clans[]','Feniks', (true if !@clans.nil? and @clans.include? 'Feniks'), class: "clan_checkbox" %>,
   Jednorożec: <%= check_box_tag 'clans[]','Jednorożec', (true if !@clans.nil? and @clans.include? 'Jednorożec'), class: "clan_checkbox" %>,
   Krab: <%= check_box_tag 'clans[]', 'Krab', (true if !@clans.nil? and @clans.include? 'Krab'), class: "clan_checkbox" %>,
   Lew: <%= check_box_tag 'clans[]', 'Lew', (true if !@clans.nil? and @clans.include? 'Lew'), class: "clan_checkbox" %>,
   Zaznacz Wszystkie: <%= check_box_tag 'select_all', 'nil', false, class: "select_all_clans" %>
 </p>
<%= submit_tag "Szukaj!" %>
<% end %>

I think this is becouse of this (true if !@clans.nil? and @clans.include? 'Lew')evaluation.

I am just starting learning CS so pleasemake full explain if possible :)

Kazik
  • 635
  • 6
  • 16

1 Answers1

0

Here you go, I hope that this is what you are looking for:

boxes = $('#checkboxlist [type=checkbox]')
selectAll = $('.selectall')    
toggleCheckboxes = ->    
    if $(this).is ':checked' then boxes.prop "checked", true else boxes.prop "checked", false

selectAll.on 'click', toggleCheckboxes

Fiddle

You should change attr() to prop().

Nothing special happening here, we have just bound toggleCheckboxes() to click event on selectAll element.

Tip: next time add javascript tag for issues like this, you'll get your solution much faster and u can convert it back to CS later.

Drops
  • 2,380
  • 16
  • 16
  • I needed to start from $(document).on 'click', '.selectall' but changing from attr() to prop() done the job. By the way can you explain why? – Kazik Jun 03 '15 at 04:32
  • https://stackoverflow.com/questions/13247058/jquery-attr-vs-prop and https://stackoverflow.com/questions/5874652/prop-vs-attr – Drops Jun 03 '15 at 07:48