简体   繁体   中英

jQuery if checkbox is checked to toggle classes

I am needed to change my jQuery code up. Instead of the label toggling the class and showing the icon I need it to where if the checkbox is checked to show to toggle those classes. I have tried prop and is but I couldn't get them to work properly. The reason for the change is I want to preload data into the form and if it's going to be checked those toggles need to reflect that change.

http://jsfiddle.net/70fbLooL/2/

EDIT

Seems to be confusion as to exactly what I am trying to do. The fiddle I provided works perfectly fine. The problem is if I want to call the form from server-side and pre-populate the form the checkbox toggles will not show that they are checked because it's based on the clicked function. I need it to be based on if the checkbox equal true or checked. That way if the value equals true from the server-side call it will toggle those classes and look like it's checked.

Here's the code that works for you:

$(".companyCheckBox").click(function () {
    if($(this).is(':checked')){
       $(this).find(".fa-check").toggle();
       $(this).toggleClass("companyLabelBackground");
    }
});

That's it.

Try this

$(".companyCheckBox").click(function () {
     var obj = $(this).prev('.companyLabel');
     if($(this).is(':checked')){
         $(obj).find(".fa-check").toggle();
         $(obj).toggleClass("companyLabelBackground");
     }
});

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