Home > Net >  Confuse when CSS label of input radio
Confuse when CSS label of input radio

Time:06-22

I am writing code to change label style when its radio is checked. Here is my code:

<body>
<div >
    <label id="daily" >
      <input type="radio" checked="checked" name="radio" >
      <span ></span>
      <em>Daily</em>
    </label><br/>
    
    <label id="weekly" >
      <input type="radio" name="radio"  >
      <span ></span>
      <em>Weekly</em>
    </label>
</div>

<script>
    $(document).on("click", 'input.radio', function () {
    if ($(this).is(":checked")) {
        $('label.checked').removeClass('checked');
        $(this).parent().addClass("checked");
    }
});
</script>
</body>

and class .checked

<style>
    .checked {
    color:green;
}
</style>

Here is the jsfiddle: https://jsfiddle.net/stern/p67qf1km/3/

Everything works fine here.

But when I change the class name from 'checked' to something else like 'active' (in CSS and jQuery), the label can not remove class when not selected (all labels are still green).

Can anyone explains that for me. Thank you very much.

CodePudding user response:

I can change the class name, you might want to refer to my code https://jsfiddle.net/15frkLpe/

<div >
    <label id="daily" >
      <input type="radio" checked="checked" name="radio" >
      <span ></span>
      <em>Daily</em>
    </label><br/>
    
    <label id="weekly" >
      <input type="radio" name="radio"  >
      <span ></span>
      <em>Weekly</em>
    </label>
</div>

.active  {
    color: green;
}

$(document).on("click", 'input.radio', function () {
    if ($(this).is(":checked")) {
        $('label.active').removeClass('active');
        $(this).parent().addClass("active");
    }
});

CodePudding user response:

You could try something like this,

$(document).on("click", 'input.radio', function () {
    if ($(this).is(":checked")) {
        $('.input-area .active').removeClass('active');
        $(this).parent().addClass("active");
    }
});

$('.input-area .active').removeClass('active');

Above code will take and remove '.active' class from all elements inside the '.input-area' and add '.active' class to the parent element.

  • Related