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.
Browse Timeline
- « Zend Framework How To: Creating your own validator for confirm passwords and emails
- » Zend Framework and Dojo Javascript Toolkit Partners
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 pmAmit Shah added these pithy words on Oct 16 08 at 5:03 pmHow could we apply any JavaScript function on checkbox?
Wenbert added these pithy words on Oct 16 08 at 5:53 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.