Jquery: Text spanned checkbox

I’m not sure what they call this, but it’s best shown with a demo. See here. The upper one is what I want to achieve, the lower one is a bad bad pampered child.

I’m not sure if there’s an easier way of doing this, but I achieved this effect using a small JQuery script.

The markup

The markup is just a form with a checkbox. But we added a <span> around the checkbox to be used by the script. Any checkbox with this span element will have the same effect. Put this between your <body> tags


<form method="post" action="#">
<span class="checkboxarea">
<input type="checkbox" name="rem"  />Checkbox description goes here
</span>
</form>

The CSS

You don’t need css really, but you probably want to have the cursor as a pointer on the text, not a text cursor. Add the following CSS rule:


.checkboxarea {cursor: default}

The script

Time for the JQuery script! First ofcuorse, you need to import the jQuery library. Add this between your <head> tags.


<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <!-- jquery -->

Finally, add the following jQuery script either inline or in a seperate file:


$(window).ready(function() {
$(".checkboxarea").click(function() {
$(this).find("input[type=checkbox]").each(function() {
this.checked = !this.checked
})
});
$(".checkboxarea > input[type=checkbox]").click(function(event) {event.stopPropagation();} );

});

And that’s it ! It should work fine now. Here’s the demo file for you.

_happy coding

This entry was posted in JQuery, Tutorial. Bookmark the permalink.

2 Responses to "Jquery: Text spanned checkbox"

Leave a reply


6 − five =