A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

jQuery: Setting defaults for Checkboxes, Radio Buttons, Options in Selectboxes

I thought I should post this here. I always tend to look back at my old code wondering how I did these things.

Handling radio buttons or checkboxes

<input type="radio" name="print_memo" value="Yes"/> Yes 
<input type="radio" name="print_memo" value="No" /> No
<script type="text/javascript" language="javascript">
$(document).ready( function () {
    $('INPUT[name=print_memo][value="<?=$this->request->print_memo?>"]').attr('checked', true)
    /**
    * $this->request->print_memo will output either 'Yes' or 'No'
    * Here, we used INPUT[name=XXX] to select the form element
    */
});

For select boxes

<select id="country_id" name="country">
    <option value="1">Philippines</option>
    <option value="2">Singapore</option>
    <option value="3">Norway</option>
</select>
$(document).ready( function () {
    $('#country_id option[value="<?=$this->request->country_id?>"]').attr('selected', 'selected');
    /**
    * $this->request->country_id will output 1,2 or 3
    * Here, we used #country_id to select the form element
    */
});
This entry was posted in General and tagged , , , , , , . Bookmark the permalink.

3 Responses to jQuery: Setting defaults for Checkboxes, Radio Buttons, Options in Selectboxes

  1. jared says:

    Good post, but couldn’t you just as easily do this for the select?

    $(‘#country_id’).val(request->country_id?>);

  2. Why are you willing to depend on JS for that kind of important feedback? Besides, it adds extra code.

  3. Wenbert says:

    The code above is merely demonstrating how to use selectors.

Leave a Reply to Carl Helmertz Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>