[How To] Custom Checkbox using jQuery

Here is how I managed to get the custom checkbox using jQuery. See the screenshot below

JQuery Custom CheckBox

JQuery Custom CheckBox

The simple idea is to put class where we want to display checkbox. Here I have used two classes .clear and .checked. The name are very obvious.

.clear holds the unchecked state of checkbox.

.checked holds the checked state of checkbox.

Whenever the click on the class .clear and .checked class is triggered, we change the background accordingly by adding and removing the corresponding CSS by jQuery, this is where we use jQuery in fact.

We have three files:

1. checkbox.html
2. checkbox.js
3. checkbox.css

Source code for checkbox.html

<html>
<head>
<title>JQuery Custom gnu CheckBox Demo</title>
<link rel="stylesheet" href="checkbox.css">
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="custom_checkbox.js"></script>
</head>
<body>
<h3>Show More Tutorials on :</h3>
		<ul id='langauges'>
			<li><p><span class='clear' rel='java'></span>Java</p></li>

			<li><p><span class='clear' rel='visual basic'></span>Visual Basic</p></li>
			<li><p><span class='clear' rel='python'></span>Python</p></li>
			<li><p><span class='clear' rel='ruby'></span>Ruby</p></li>
			<li><p><span class='clear' rel='c/c++'></span>C/C++</p></li>
		</ul>

	<p class='show_value'></p>

</body>
</html>

Sourcecode for custom_checkbox.js

$(document).ready(function() {
	var opt = $('p &gt; span');
	$(opt).click(function() {
		var value = $(this).attr('rel');

		if ($(this).hasClass('clear')) {
			$(this).removeClass('clear');
			$(this).addClass('checked');
			$('.show_value').text("Checked : "+value);
		} else {
			$(this).removeClass('checked');
			$(this).addClass('clear');
			$('.show_value').text("Unchecked : "+value);
		}
	});
});

Sourcecode for checkbox.css

body {
	background:#000;
	color:#fff;
}
ul#langauges {
	list-style:none;
	width:80%;
}
ul#langauges li {
	width:70%;
}

span.checked {
	background-image:url('checked.png');
	background-repeat:no-repeat;
	background-position:50% 50%;
}

span.clear {
	background-image:url('clear.png');
	background-repeat:no-repeat;
	background-position:50% 50%;
	}

.clear,.checked {
	float:left;
	margin-right:5px;
	display:block;
	background-image:url('clear.png');
	background-repeat:no-repeat;
	background-position:50% 50%;
	width:22px;
	height:22px;
}

That’s all, try and enjoy it.

Leave a Reply

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