jQuery: How to handle radio buttons

Filed Under (General) by Wenbert on 03-07-2008

Tagged Under : ,

Here is a quick tutorial on how to handle radion buttons using jQuery.

< input type="radio" name="empType" value="regular" /> Regular
< input type="radio" name="empType" value="temporary" /> Temporary

Then the jQuery code: (assuming that you have already included the JS file in the header…)

 $("input[@name='empType']").change(
        function() {
            if ($("input[@name='empType']:checked").val()) {
                alert($("input[@name='empType']:checked").val());
            }
        }
    );

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.

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.

Mixing PHP Variables with Javascript (Zend Framework and jQuery)

Filed Under (General) by Wenbert on 23-04-2008

Tagged Under : , , ,

Sometimes, I “mix” PHP variables with Javascript. For example, I have something like this:

function deletenote(notes_id)
{
    if(!confirm("Delete note? You will not be able to undo this action."))
        return false;
       
    $.post("< ?=$this->baseUrl?>/notes/deletenote",{
        skeedl_notes_id: notes_id
    }, function(data){
        $(‘#notes_id’+data).fadeOut();
    });
}
 

Note the $this->baseUrl, I need it like that. The thing is, I have that code in my view file (.phtml - in Zend Framework, this is parsed like a normal PHP file). If I remove all the Javascript in my view file and place it in a .js file, the $this->baseUrl will not be parsed. To go around this, I create a hidden input element in my view file with $this->baseUrl echoed as the value. Like this:

// … in my .phtml file …
// rest of the php and html code goes here
< input type="hidden" id="base_url" value="<?=$this->baseUrl?>" />
// rest of the php and html code goes here
 

Then in my .js file (assuming that you have already included this file in your header, or somewhere else), I have something like this:

//This is using jQuery, but you can use document.getElementById(’base_url’).value if you like
function deletenote(notes_id)
{
    if(!confirm("Delete note? You will not be able to undo this action."))
        return false;
       
    $.post($(‘base_url’).val()+"/notes/deletenote",{
        skeedl_notes_id: notes_id
    }, function(data){
        $(‘#notes_id’+data).fadeOut();
    });
}
 

What it does is that jQuery gets the value of the hidden form element. The value of this hidden form element is from a PHP Variable.

So there you go, nothing special. Just something that works and I just wanted to share.

Get name of textarea or input using jQuery

Filed Under (General) by Wenbert on 28-03-2008

Tagged Under : ,

You can do this in jQuery:

$("textarea[@name=my_field_name]").val()
$("input[@name=my_field_name]").val()

Check Multiple Checkboxes in one click using jQuery

Filed Under (General) by Wenbert on 24-03-2008

Tagged Under : ,

This is useful if you want to “delete” or “update” multiple rows in a table at the same time. This works like the “Check All Email” in YahooMail.

$(document).ready(function() {
    //check all checkboxes
    $("#check_all_boxes").click(function() {
        $(".mycheckbox").each(function(i){
            $(this).attr("checked","checked");
        });
    });

    //uncheck all checkboxes
    $("#uncheck_all_boxes").click(function() {
        $(".mycheckbox").each(function(i){
            $(this).removeAttr("checked");
        });
    });

    //reset the search form
    $("#reset_button").click(function() {
        $("#search_form input").each(function(i) {
            //alert($(this).html());

        });
    });

});

And the HTML Code is:

< input class="mycheckbox" name="a" value="1" type="checkbox" />Number 1
< input class="mycheckbox" name="b" value="1" type="checkbox" />Number 2
< input class="mycheckbox" name="c" value="1" type="checkbox" />Number 3
< a href="#" id="#check_all_boxes">Check All< / a>
< a href="#" id="#uncheck_all_boxes">Uncheck All< / a>

Hightlight a table row on click using jQuery

Filed Under (General) by Wenbert on 19-02-2008

Tagged Under : , ,

The scenario: Every time you click on a row, the row highlights. When you click on the highlighted row - remove the highlight.
The jQuery / Javascript code:

//highligths the clicked row
function highlightrow(obj) {
    if ($(obj).attr("style")==‘background-color: rgb(255, 255, 187);’ || $(obj).attr("style")==‘BACKGROUND-COLOR: #ffffbb’) {
        $(obj).removeAttr("style");
    } else {
        $(obj).attr("style","background-color: #FFFFBB;");
    }
}
 

And for the HTML Code:

..rest of the HTML tags here…
< tr onclick="highlightrow(this);" >
..rest of the HTML tags here…
 

jQuery: Select all options in a Multiple-option Select Box

Filed Under (General) by Wenbert on 04-02-2008

Tagged Under : , ,

Alright, here is a quick example of how to use jQuery to select all of the items in a multiple-option select box.

//Javascript part assuming that you have already included jquery.js in your header
$(document).ready(function() {
    $("#select_all_col_managers").click(function() {
        $("#col_manager_list").each(function(){
            $("#col_manager_list option").attr("selected","selected"); });
    }) ;

    $("#unselect_all_col_managers").click(function() {
        $("#col_manager_list").each(function(){
            $("#col_manager_list option").removeAttr("selected"); });
    }) ;

});

and now for the HTML part…

Filter by Collection Manager:
< select class="select_multiple" id="col_manager_list" multiple="multiple" name="RTCLMG[]">
< option>Must Select One
< option> value="< ?=$value['col_manager']?>">< ?=$value['col_manager']?>        < / select>

    < a href="#" id="select_all_col_managers">Select All< / a> 
    < a href=”#” id=”unselect_all_col_managers”>Unselect All< / a> 

Please note that I am using Code Igniter with this.

Handling HTML Checkboxes. Execute something when checked/unchecked.

Filed Under (General) by Wenbert on 23-11-2007

Tagged Under : ,

In some cases, you are required to do something (EG: show/hide divs) when a checkbox is clicked. Here is an example using jQuery.

First your checkbox will look like this:

...html code here...

< input name="myCheckBox" id="myCheckBox" value="yes" type="checkbox" /> This is a sample checkbox.

Then somewhere in your HTML head, your Javascript code will look like this:

other code here…

    $(‘#myCheckBox’).click(function(){
        if (this.checked) {      //this.checked is NOT from jquery
            alert(‘Do any action here.’);
        } else {
            alert(‘Undo the action here.’);
        }
    });

other code here…

NOTE: Do not forget to download and then include the required jQuery files in your HTML File.

jQuery on Ruby on Rails

Filed Under (General) by Wenbert on 22-11-2007

Tagged Under : , , ,

I found this:

jRails is a drop-in jQuery replacement for Prototype/script.aculo.us on Rails. Using jRails, you can get all of the same default Rails helpers for javascript functionality using the lighter jQuery library.

jRails provides drop-in functionality for these existing Rails methods.

o Prototype
o form_remote_for
o form_remote_tag
o link_to_remote
o observe_field
o observe_form
o periodically_call_remote
o remote_form_for
o submit_to_remote

o Scriptaculous
o draggable_element
o drop_receiving_element
o sortable_element
o visual_effect

o RJS
o hide
o insert_html
o remove
o replace
o replace_html
o show
o toggle

Click here.

jQuery AJAX in Zend Framework

Filed Under (General) by Wenbert on 28-08-2007

Tagged Under : , ,

I have posted a sample code on my wiki on how to submit variables to an action controller. The sample code contains a niffty jQuery plugin - the jQuery Calendar.

Click here for the tutorial.

Update (05-07-2008): Since this post has been getting a lot of traffic and the tutorial to my wiki is not that good, I have decided to update this page and post a simpler and shorter tutorial.

So here it is…

The Javascript will look something like this:

//For Edit Action
f u n c t i o n editnote(notes_id)
{
    //a sample loading image thingy
    $(‘#notes_entry_id’).prepend("<div id=’loading’><img src=’"+baseUrl+"/images/loading.gif’/></div>");
    //Get notes from database - in ZF, notes = controller and getnoteforedit = action
    $.post(baseUrl+"/notes/getnoteforedit",{
        notes_id: notes_id
    }, function(data){
        $(‘#loading’).remove();
        obj = window.eval(data);
        $(‘#textarea_id’).val(obj[‘notes’]);
    }, "json"); //this returns JSON.
}
 

Then my controller would look something like this:

    /**
     * Get note for action
     *
     */

    public function getnoteforeditAction()
    {
        $this->_helper->layout->disableLayout();    //disable layout
        $this->_helper->viewRenderer->setNoRender(); //suppress auto-rendering
        //the 2 lines above are very important. this action would return html tags from the layout and will look for a phtml file. we disable the layout and suppress auto-rendering of the phtml view files SO that our JSON will be echoed properly to the Javascript…
        require_once(‘models/Notes.php’);
        require_once(‘models/UsersNotes.php’);
        try {
            if (!$this->_request->isPost()) {
                throw new Exception(‘Invalid action. Not post.’);
            }
            $Notes = new Notes();
            $data = array();
            if ($result = $Notes->fetchRow("notes_id=".$Notes->getAdapter()->quote($_POST[‘notes_id’])."")->toArray()) {
                $data[‘notes_id’]             = $result["notes_id"];
                $data[‘notes’]                = $result["notes"];
                $data[‘datetime_posted’] = $result["datetime_posted"];
                $data[’status’]               = $result["status"];
                $json = Zend_Json::encode($data);    //basically, $data array will also be available in the JS.
            } else {
                throw new Exception(‘Note ID not found.’);
            }
            echo $json; //this will echo JSON to the Javascript
            unset($json);
            unset($data);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
 

That’s about it… :D
The $data that was encoded using Zend_JSON in the controller/action can now be accessed in the Javascript after you call the eval().

Subscribe to Rss Feed : Rss