Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How to make the user choose at least one checkbox in a form?

I have a form, where a user has to check at least one checkbox before submitting the form. Is there any plugin that can handle this or maybe jquery that can be applied to my form? Unfortunately I'm a total jquery rookie.

like image 389
Mexxer Avatar asked Dec 28 '22 15:12

Mexxer


2 Answers

All the answers above show how to do this client-side, which may indeed be preferable. As your question title indicates you're using Rails 3, you could also validate this server-side:

class Example < ActiveRecord::Base
  ...
  validates :something_was_checked

  ...
  private

  def something_was_checked
    if self.checkbox_attribute.blank?
      self.errors.add(:checkbox_attribute, "You must select at least one option.")
    end
  end
end
like image 174
Andrew Avatar answered Dec 30 '22 04:12

Andrew


You can use a simple jQuery to do that

$("form").submit(function(){

   if($(this).find("input:checked").length == 0){
     //No checkbox checked
     return false;
   }
});
like image 41
ShankarSangoli Avatar answered Dec 30 '22 05:12

ShankarSangoli