开发者

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.


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


You can use a simple jQuery to do that

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

   if($(this).find("input:checked").length == 0){
     //No checkbox checked
     return false;
   }
});


The jQuery Validation Plugin can provide this functionality. You can see a demo of how to implement it for requiring a checkbox here.

Basically, once you load the JavaScript file for the validation plugin on your page, you'll need to initialize the validator for the form you want to validate. The JavaScript to do this will look something like:

$('#form1').validate();

The checkboxes will need to be wrapped in a <fieldset> tag. The validation of the fieldset can then be activated by adding a validate attribute to the input tag for the checkbox. For example:

    <input type="checkbox" validate="required:true" />

The validation will then be triggered when the form's submit button(s) are clicked.


Sure, you can do that.

 if($('.myCheckBox :selected').length == 0)
     alert('Select a check box foo!');

You simply query for your checkboxes with the :selected modifier, and check the length.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜