开发者

Change current element background in jQuery

开发者 https://www.devze.com 2023-01-28 00:30 出处:网络
<label class=\"default\" for=\"checkbox1\"><input id=\"checkbox1\" name=\"checkbox1\" type=\"checkbox\" style=\"display:none\" /> some text开发者_StackOverflow</label><br />
<label class="default" for="checkbox1"><input id="checkbox1" name="checkbox1" type="checkbox" style="display:none" /> some text开发者_StackOverflow</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 />


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. ;)


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');
});


$("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");
});
0

精彩评论

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