jquery - check box checked when click in associated label -



jquery - check box checked when click in associated label -

i have checkbox , description of checkbox in label.i want check checkbox when label clicked. markup:

<input id="checkbox1" type="checkbox" /></div> <label id="lblassociatewithcheckbox" title="check"></label>

in jquery try:

$(document).ready(function() { checkcheckbox($('lblassociatewithcheckbox'), $('checkbox1')); function checkcheckbox(lblid, chkid) { $('#' + lblid).live("click", function() { homecoming $('#' + checkbox1).attr('checked', 'checked'); }); } });

but not work.i got error in firebug.

uncaught exception: syntax error, unrecognized expression: #[object object]

what error ? if not proper way suggest alternative way.thanks.

update: saw comment under pavan's reply wanting utilize non-label elements labels, e.g., span elements. first response why? if want can without having write lots of code , hardcode lots of element ids in javascript (which seems path you're on existing code).

use data attribute in element want utilize pseudo-label, follows:

<span data-labelfor="name">name</span> <input type="checkbox" id="name">

and can setup click handler generic jquery select elements attribute:

$(document).ready(function() { $("[data-labelfor]").click(function() { $('#' + $(this).attr("data-labelfor")).prop('checked', function(i, oldval) { homecoming !oldval; }); }); });

working demo shows 1 short function applying behaviour span label , div: http://jsfiddle.net/tfd72/

original answer:

as pavan explained, can automatically using for attribute in label, far why code didn't work:

your phone call checkcheckbox() function passing 2 jquery objects parameters follows:

checkcheckbox($('lblassociatewithcheckbox'), $('checkbox1'));

but function treating parameters if strings holding ids of elements want process. if want maintain function alter way phone call pass right sort of parameter:

checkcheckbox('lblassociatewithcheckbox', 'checkbox1');

that should prepare error quote.

however, function set checkbox "checked" on every click of label, if checked. if want toggle between checked , unchecked (i.e., normal behaviour) can this:

$('#' + checkbox1).prop('checked', function(i, oldval) { homecoming !oldval; });

(but again, in html markup using for attribute.)

jquery checkbox

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -