Sunday, April 10, 2011

Custom radio button/checkbox - jQuery


Hi,

This can be considered as a continuiton of my previous post for creating custom dropdown using jQuery. In web 2.0 it becomes important to get rid of the conventional flat looking radio buttons and check box with stylish images but keeping their functionality. In this post I have made a custom solution for achieving that. Click here to download the entire source code.

I am using 2 pair of images. 1 pair for selected/unselected radio buttons and other checked/unchecked check boxes. First lets take a look how it looks:


Explanation:
First download the source code. All the trick is in the script.js file. You just need to follow few conventions given below for defining a radio button or a checkbox:

Radio button:
Conventionally this is what we write:
<input type="radio" value="male" name="gender" checked> Male, but in this case we will wrap it inside a div as follows (keep note of the sections with bold text):


<div>
<div rel="radio" rclass="gender" rid="g_male" class="selected_radio">
<br><input type="radio" class="gender" id="g_male" value="male" name="gender" checked style="display:none">
</div>
Male
</div>

Here we have the following custom attributes:

rclass: refers to the name of the element i.e. name of the radio button input field. We need to add a class to radio button element with the rclass value. In the above case the value is "gender".

rid: this is just the unique ID of  each radio button used. The "rid" of the wrapping div should be same as the "rid" of the radio button element inside the div. In the above case the "rid" is "g_male"

Checkbox:
Conventionally this is what we write:

<input type="checkbox" value="shopping" name="interests[]"> Shopping, but in this case it will be:

<div>
<div rel="checkbox" rclass="shopping" rid="i_shopping" class="default_checkbox">
<br><input type="checkbox" class="shopping" id="i_shopping" value="shopping" name="interests[]" style="display:none">
</div>
Shopping
</div>

here also the naming conventions are the same as that of the above radio buttons.

Now when we submit the form this is the $_POST array that is being generated:

Array
(
    [gender] => male
    [interests] => Array
        (
            [0] => music
        )

    [cuisine] => Array
        (
            [0] => chineese
            [1] => mexican
        )

    [submit] => Update
)

Now our custom radio button/checkbox is ready. For more clarification or customisation post in your comment or mail me at phpdrops@gmail.com.

Download: custom_radiobutton_checkbox.zip 

No comments:

Post a Comment