简体   繁体   中英

Change current element background in jQuery

<label class="default" for="checkbox1"><input id="checkbox1" name="checkbox1" type="checkbox" style="display:none" /> some text</label><br />
<label class="default" for="checkbox2"><input id="checkbox2" name="checkbox2" type="checkbox" style="display:none" /> some text</label><br />
<label class="default" for="checkbox3"><input id="checkbox3" name="checkbox3" type="checkbox" style="display:none" /> some text</label><br />

How should I change the currently clicked checkbox's label background color using jQuery? For example when the second checkbox is checked it's style should be changed with "checked":

<label class="checked" for="checkbox2"><input id="checkbox2" name="checkbox2" type="checkbox" style="display:none" /> some text</label><br />

You need to handle the change event and set the background color after checking whether this.checked .
For example:

$(':checkbox').change(function() { 
    $(this).css('background-color', this.checked ? 'red' : 'transparent');
});

There is a checkbox selector in jQuery, so using that, assign the click function to grab the parent "label" element and toggle the css class to "checked". This will add the class and remove the class depending on the state of the checkbox.

$("input:checkbox").click(function() { $(this).parent("label").toggleClass("checked");

Also, you will have more luck with your css class names if you do:

<label class="checked" for="checkbox2"><input id="checkbox2" name="checkbox2" type="checkbox" style="display:none" /> some text</label><br />

instead of what you did above. ;)

$("input[@type='checkbox']").click(function(){
     $(this).toggleClass('checked');

});

Your html should look more like this:

    <input id="checkbox1" name="checkbox1" type="checkbox" style="display:none" />
<label style="default" for="checkbox1"> some text</label><br />

The jQuery will look like this:

$("input[type=checkbox]").select(function() {
    $(this).toggleClass("checked");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM