Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check box checked when click in associated label

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.

like image 839
4b0 Avatar asked Feb 01 '12 07:02

4b0


2 Answers

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/

like image 106
Justin Avatar answered Oct 30 '22 13:10

Justin


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/

like image 34
Pavan Avatar answered Oct 30 '22 13:10

Pavan