Reputation: 103
I am writing code to change label style when its radio is checked. Here is my code:
<body>
<div class="input-area input-area-sp">
<label id="daily" class="container-radio checked">
<input type="radio" checked="checked" name="radio" class="radio">
<span class="checkmark"></span>
<em>Daily</em>
</label><br/>
<label id="weekly" class="container-radio">
<input type="radio" name="radio" class="radio">
<span class="checkmark"></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.
Upvotes: 0
Views: 38
Reputation: 36
I can change the class name, you might want to refer to my code https://jsfiddle.net/15frkLpe/
<div class="input-area input-area-sp">
<label id="daily" class="container-radio active ">
<input type="radio" checked="checked" name="radio" class="radio">
<span class="checkmark"></span>
<em>Daily</em>
</label><br/>
<label id="weekly" class="container-radio">
<input type="radio" name="radio" class="radio">
<span class="checkmark"></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");
}
});
Upvotes: 2
Reputation: 348
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.
Upvotes: 0