Iacutone.rb

coding and things

Hiding Multiple Checkboxes With JQuery

| Comments

I have been developing a quiz app for practice with a more complex schema interface. I wanted to dive deeper into CoffeScript and found the opportunity while trying to figure out how a student can add an answer to a given quiz. If a checkbox for a given answer is checked, I wanted the remaining checkboxes to disappear. Also, if the student checked the incorrect box, the browser should render all checkboxes again. Here is my code.

questions.js.coffee
1
2
3
4
5
6
7
8
9
   $('form').on 'click', '.checker', (event) ->
      boxes = $(":checkbox:checked")
      nboxes = $(":checkbox:not(:checked)")
      if boxes.length == 1
          $('.checker_label').hide()
          nboxes.hide()
      if boxes.length == 0
          $('.checker_label').show()
          nboxes.show()

... and the view

_form.html.haml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Quiz:
= @quiz.name

= form_for @question do |f|
  = f.hidden_field :quiz_id, value: @quiz.id
  = f.label "What is your question?"
  = f.text_field :content
  %br
  %fieldset
      = f.fields_for :answers do |builder|
          = builder.label :content, "Answer"
          = builder.text_field :content
          = builder.label "Correct answer?", class:'checker_label'
          = builder.check_box :is_correct, class: 'checker'
      %br
  = link_to_add_fields "Add an answer choice", f, :answers
  %br
  = f.submit

Comments