Zend Framework How To: Handling checkboxes using Zend_Form and jQuery

Filed Under (General) by Wenbert on 20-05-2008

Tagged Under : , ,

I am sharing this because it took me a while to figure out how to handle checkboxes using jQuery.

First off, let us create a checkbox using Zend_Form.

  1.  
  2. class forms_CoolForm extends Zend_Form
  3. {
  4.     public function __construct($options = NULL)
  5.     {
  6.         parent::__construct($options);
  7.         $this->setName(‘cool_form’);
  8.  
  9.         $content = new Zend_Form_Element_Textarea(‘notes’);
  10.         $content->setLabel(‘Content’)
  11.                 ->setAttrib(‘class’,‘my_textarea’)
  12.                 ->setAttrib(‘id’,‘textarea_id’)
  13.                 ->addValidator(‘NotEmpty’)
  14.                 ->setRequired(true);
  15.                
  16.              
  17.         $submit = new Zend_Form_Element_Button(‘button’);
  18.         $submit->setLabel(‘Go’)
  19.                ->setAttrib(‘class’,‘my_submit’)
  20.                ->setAttrib(‘id’,’submit_id’);
  21.        
  22.         $ispublic = new Zend_Form_Element_Checkbox(‘is_public’);
  23.         $ispublic->setLabel(‘Allow anyone to view this post?’)
  24.                  ->setAttrib(‘id’,‘is_public’);
  25.  
  26.         $this->addElements(array($content, $ispublic, $submit));
  27.     }
  28. }
  29.  

The code for the Zend_Form_Element_Checkbox above will generate something like this:

  1.  
  2. <input type="checkbox" value="0" id="is_public" name="is_public"/>
  3.  

Notice that the value is always Zero? Usually, in jQuery, we get used to getting the value of inputs using:

  1.  
  2. $(‘#is_public’).val();
  3.  

With that we can do all sort of things. But .val() will always return “0″. So the trick is, you need to check if the checkbox is “Checked” using something like this:

  1.  
  2. if($(‘#is_public’).is(‘:checked’)) {
  3.     temp_public = ‘yes’;
  4. } else {
  5.     temp_public = ‘no’;
  6. }
  7. //then you send temp_public to other functions — AJAX stuff or DOM modification
  8.  

That’s about it. Basically it just the .is() in jQuery.

Subscribe to Rss Feed : Rss