Reputation: 327
Hello i made a script that is supposed to change background when radio is selected. It works but when another radio is selected the previous still remains with the selected color. It works for checkboxes but not for radio.
<script type="text/javascript">
$(".table").change(function(){
var c = this.checked ? "#18b9e7" : "#b6bf34";
$(this).parent().css("background-color", c);
});
</script>
Here is a jsfiddle
Upvotes: 0
Views: 219
Reputation: 17366
I think you need this:
Your fiddle contains checkboxes instead radio buttons, make sure it's radios or checkboxes.
$('.table').change(function(){
var c = this.checked ? '#00B0EA' : '#B6BF34';
$(this).parent().css('background-color', '#00B0EA').siblings().css('background-color', '');
});
Upvotes: 3
Reputation: 749
The problem with the radio buttons are that once you change the value of one automatically deselects the other ones but just trigger the change event on the clicked control, you need to check for all controls and apply the same logic everytime the change event are triggered:
$('.table').change(function(){
$('.table').each(function(){
var c = this.checked ? '#00B0EA' : '#B6BF34';
$(this).parent().css('background-color', c);
});
});
Upvotes: 0
Reputation: 4414
I would handle it like so:
var $labels = $(".m1");
$('.table').change(function(){
var c = this.checked ? '#00B0EA' : '#B6BF34';
$labels.removeAttr("style");
$(this).parent().css('background-color', c);
});
Cache the reference to your $labels
outside of the change
handler.
Upvotes: 0
Reputation: 4426
This is simplier:
$(".table").change(function(){
$(".table").parent() //all the inputs
.css("background-color", "#b6bf34"); //to be green
$("input[name=masa]:checked").parent() //only the checked
.css("background-color", "#00B0EA"); //to be blue
});
Upvotes: 0
Reputation: 2019
add a
$(ALL RADIOS SELECTOR).css('background-color', DISABLED_COLOR)
before the change for example
$(".table").change(function() {
var $this = $(this),
c = this.checked ? "#18b9e7" : "#b6bf34"
$this.find('input[type="checkbox"]').parent().css('background-color', "#b6bf34");
$this.parent().css("background-color", c);
});
change checkbox to radio if necessary
Upvotes: 0