I have a checkbox
and a description of the checkbox in label
. I want to check
Checkbox when label is clicked.
Markup:
<input id="Checkbox1" type="checkbox" /></div>
<label id="lblAssociateWithCheckBox" title="Check"></label>
In jQuery I try:
$(document).ready(function() {
CheckCheckBox($('lblAssociateWithCheckBox'), $('Checkbox1'));
function CheckCheckBox(lblID, chkID) {
$('#' + lblID).live("click", function() {
return $('#' + Checkbox1).attr('checked', 'checked');
});
}
});
But it does not work. I got an error in Firebug.
uncaught exception: Syntax error, unrecognized expression: #[object Object]
What is my mistake? If this is not a proper way to do this suggest an alternative way.
There are two ways to do this without any JavaScript at all. Pavan explained the first way, which is to use the for
attribute (match the checkbox id):
<input id="Checkbox1" type="checkbox" />
<label for="Checkbox1" title="Check">Check ME</label>
The other way, which I prefer is to wrap the checkbox within a label tag:
<label><input type="checkbox" id="Checkbox1"> Text</label>
Here is the JSFiddle for both: http://jsfiddle.net/m4rK5/
You don't need to write jQuery code. You can do this with HTML.
Change your HTML content as below:
<input id="Checkbox1" type="checkbox" />
<label for="Checkbox1" title="Check">Check ME</label>
Here is the JSFiddle: http://jsfiddle.net/sjG4w/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With