Zend Framework How To: Handling checkboxes using Zend_Form and jQuery

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.

class forms_CoolForm extends Zend_Form
{
    public function __construct($options = NULL)
    {
        parent::__construct($options);
        $this->setName('cool_form');
 
        $content = new Zend_Form_Element_Textarea('notes');
        $content->setLabel('Content')
                ->setAttrib('class','my_textarea')
                ->setAttrib('id','textarea_id')
                ->addValidator('NotEmpty')
                ->setRequired(true);
 
 
        $submit = new Zend_Form_Element_Button('button');
        $submit->setLabel('Go')
               ->setAttrib('class','my_submit')
               ->setAttrib('id','submit_id');
 
        $ispublic = new Zend_Form_Element_Checkbox('is_public');
        $ispublic->setLabel('Allow anyone to view this post?')
                 ->setAttrib('id','is_public');
 
        $this->addElements(array($content, $ispublic, $submit));
    }
}

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

<input type="checkbox" value="0" id="is_public" name="is_public"/>

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

$('#is_public').val();

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:

if($('#is_public').is(':checked')) {
    temp_public = 'yes';
} else {
    temp_public = 'no';
}
//then you send temp_public to other functions -- AJAX stuff or DOM modification

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


Subscribe to comments Comment | Trackback |
Post Tags: , ,

Browse Timeline


Comments ( 4 )

[…] blog post shows how to create checkboxes with Zend_Form and handle them with jQuery. Author gives commented […]

ZF: Handling checkboxes using Zend_Form and jQuery | PHP Readings added these pithy words on May 20 08 at 6:30 pm

Thanks for sharing!It might usefull for me.

Luca added these pithy words on May 21 08 at 2:22 am

How could we apply any JavaScript function on checkbox?

Amit Shah added these pithy words on Oct 16 08 at 5:03 pm

@Amit Shah, use jQuery and do something like this:

if($(‘#is_public’).is(‘:checked’)) {
//blah
}

where #is_public is the ID of the checkbox.

Wenbert added these pithy words on Oct 16 08 at 5:53 pm

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> <pre lang="" line="">


© Copyright 2007 eKini: Web Developer Blog . Thanks for visiting!