I’m using this code:
$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
var switches = $(this).parent().find('.switch');
$(switches).attr('state','on')
$(switches).css({'left':"52px"});
$(switches).parent().css({'background-position': "147px -37px"});
}})
But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?
Thanks for your help 🙂
EDIT:
here is the HTML
<fieldset>
<input checked="checked" />
<label></label>
<div class="toggle_box">
<div class="switch" state="on"></div>
</div>
</fieldset>
<fieldset>
<input/>
<label></label>
<div class="toggle_box">
<div class="switch"></div>
</div>
</fieldset>
You’re passing the
checkedvalue toattr()as the second argument. That causes it to be set. What’s then returned is the jQuery object with thatinput, which is always a truthy value.Your if condition should look like this (use the
:checkedpseudo-class instead):On a side note, your inner code can be refactored to this:
If you have to use a cached variable (i.e.
switches), you can, but don’t wrap it in the jQuery function. It’s a jQuery object itself, so needs not be wrapped.