开发者

jQuery to bind click behavior to a collection of matching elements

开发者 https://www.devze.com 2023-03-20 04:52 出处:网络
I\'d like to add a jQuery handler for each of my checkbox inputs so that when their value is changed (via a click directly on them or via a click on the labels bound to them via the \"for\" attribute)

I'd like to add a jQuery handler for each of my checkbox inputs so that when their value is changed (via a click directly on them or via a click on the labels bound to them via the "for" attribute), to true (or checked="checked") a class called "selected" is added to the parent li element.

Conversely, when the checkbox is unchecked by a click event, I want to remove the "selected" class from the li element.

<li class="section">
    <label class="left" for="my_ad_stacked">Left Label</label>
    <input type="checkb开发者_如何学Goox" name="my_ad_stacked" id="my_ad_stacked" value="true"  />
    <label for="my_ad_stacked" class="description check ">label info goes here</label>
</li>

I know that If I know the id or class of an element, I can use $('myElement').addClass('selected') and $('myElement').removeClass('selected'). I'm just not certain how to attach the behavior, dynamically to all checkbox elements, and their "for" bound labels.


$("input[type=checkbox]").change(function() {
   $(this).closest("li").toggleClass("selected");
});

This binds a change event to every input element of type checkbox. When one changes, the event handler function runs, and toggles the selected class on the closest li element.

In the event handler, this refers to the checkbox that has changed, so this will work for all checkboxes (assuming all checkboxes on your page have an li element ancestor).

Here's an example fiddle showing this in action.


$(":checkbox, :checkbox + label").click(function()
{
    var li = $(this).closest("li");
    var chk = $(this).parent().find(":checkbox");

    if(chk.is(":checked")) li.addClass("selected");
    else li.removeClass("selected");
});


$(':checkbox').change(function(){
    var $checkbox = $(this),
        $li = $checkbox.parents('li');
    if($checkbox.is(':checked')){
        $li.addClass('selected');
    } else{
        $li.removeClass('selected');
    }
});

Test it here »

0

精彩评论

暂无评论...
验证码 换一张
取 消