Add Class to Label of Defaulted Checked Checkbox and Radio

I've found a lot of example of this, but none with exactly what I'm trying to do in one nugget. I need to change the label (the label must be wrapped around the input for my fancy inputs) of the checkbox or radio depending if the checkbox or radio is "checked." Some of these inputs will be checked upon arriving at the form, so the class needs to show upon arrival if checked.

It's working now for checkboxes, but how do I add radio buttons into the mix without breaking it? Appreciate the help!

Here's my HTML/CSS:

<style type="text/css">
.c_on {color: #F0F;}
.r_on {color: #0F0;}
</style>

<fieldset class="checkboxes">

    <label for="chk1"><input type="checkbox" id="chk1" />chk1</label><br />
    <label for="chk2"><input type="checkbox" id="chk2" checked="checked" />chk2</label>

</fieldset>

<fieldset class="radios">

    <label for="rdo1"><input type="radio" name="group1" id="rdo1" />rdo1</label><br />
    <label for="rdo2"><input type="radio" name="group1" id="rdo2" checked="checked" />rdo2</label>

</fieldset>

Here's my jQuery:

$(document).ready(function() {

    /* Turn checkbox class on */
    var checkOn = 'c_on'

    function toggleLabelClass(input){
        var $input = $(input);
        if ($input.is('[type="checkbox"]:checked')){
            $input.parent('label').addClass(checkOn);
        }else{
            $input.parent('label').removeClass(checkOn)
        }
    }
    $(function() {
        $('input[type="checkbox"]').each(function(){
            toggleLabelClass(this);
            $(this).click(function(evt){
                toggleLabelClass(evt.target);
            });
        });
    });

});

http://jsfiddle.net/P2n2V/


Maybe something like this will work :

$(function() {
    var inputOn = 'c_on',
        radioOn = 'r_on',
        elms=$('input[type="checkbox"], input[type="radio"]');

    function setLabelClass() {
        elms.each(function(i,e) {
            $(e).parent('label')[e.checked?'addClass':'removeClass']($(e).is(':radio')?radioOn:inputOn);
        });
    }

    elms.on('change', setLabelClass);
    setLabelClass();
});​

FIDDLE


You need to add radio inputs to the each() loop and make some changes to the toggleLabelClass() function. Is this is what you need: http://jsfiddle.net/zjc9e/

I am not sure what do you mean by not breaking the mix. Are there any parts of the code you do not want to change?

链接地址: http://www.djcxy.com/p/83148.html

上一篇: addClass和removeClass在IE8中不起作用

下一篇: 将类添加到默认选中复选框和收音机标签