I came up with this jQuery snippet to add/remove a class on <label> tags that contain either checkboxes or radio buttons, in order to improve usability so users can see what item(s) they have selected.But I would like to know if there's a way to optimize the code (or not if that's the case).$('label input[type=radio], label input[type=checkbox]').click(function() {  $('label:has(input:checked)').addClass('active');  $('label:has(input:not(:checked))').removeClass('active');});
Add/remove class to label tags
javascript;jquery
I know you've marked this question answered, but since this website is about 'code review', and further improvements are possibleYou're currently attaching event-handlers on each checkbox, which is inefficient, it's far more efficient to use 'delegation', making use of event-bubbling. Reducing the amount of event-handlers is better for performance and reduces the risk for memory-leaks, especially if you're adding/removing elements to your page dynamically.More information on Event Delegation:In general: http://davidwalsh.name/event-delegatejQuery.on(): http://api.jquery.com/on/#direct-and-delegated-events With jQuery, you can make use of 'delegation' by putting a .on() event handler on a parent element. A performance comparison can be found herehttp://jsperf.com/jquery-live-vs-delegate-vs-on/34(although you're not using the .live() function, it is to illustrate using separate event-handlers vs. a single handler/delegation)Here's some information that explains how it works:http://www.jquery4u.com/jquery-functions/on-vs-live-review/For your specific example, the code would be like this:$(document).on('click', 'label input[type=checkbox]').click(function() {    $(this.parentNode).toggleClass('active', this.checked);});This will create a single event-handler that handles all click events on 'checkboxes' if they are wrapped in a label like this:<label><input type='checkbox' id='check1' value='1' />Check me</label>However, if you don't 'wrap' your input in a label, but have them separate, using the 'for' attribute:<input type='checkbox' id='check1' value='1' />  <label for='check1'>check me</label>Then the code above won't work, in this case you'll have to select the label in a different way:$(document).on('click', 'input[type=checkbox]').click(function() {    $(label[for=' + this.id + ']).toggleClass('active', this.checked);});