Reputation: 179
I have two separate sets of radio buttons and I want its' divs' color to change when its selected. The behavior I want is quite straightforward, if the radio button is selected, the corresponding div should change color. (And change back to its original color if deselected).
However, the issue is if a radio button in another set is selected, the first set's div changes back to its original color even though one of its radio buttons is still selected. How do I fix this?
Jquery used:
$(document).ready(function(){
$('input:radio').change(function(){
$('div.highlight').removeClass('highlight');
$(this).closest('div').addClass('highlight');
});
});
Upvotes: 0
Views: 11696
Reputation: 456
Not jQuery, but you could look into css rules (the nesting is important: the div.highlight and radio need to be siblings):
div.entry {
position: relative;
padding: 8px;
width: 50%;
}
div.entry div.highlight {
background-color: #fff;
position: absolute;
z-index: -1;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
div.entry input:checked ~ div.highlight {
background-color: orange;
}
<div class="entry">
<input type="radio" name="list" />This is one option
<div class="highlight"></div>
</div>
<div class="entry">
<input type="radio" name="list" />This is another option
<div class="highlight"></div>
</div>
<div class="entry">
<input type="radio" name="list" />This is a third option
<div class="highlight"></div>
</div>
Upvotes: 1
Reputation: 55740
For the 2nd issue you need to wrap your's inputs for a block into a separate wrapper and change a bit of your code..
JS
$(document).ready(function(){
$('input:radio').change(function(){
var $this = $(this);
// Only remove the class in the specific `box` that contains the radio
$this.closest('.box').find('div.highlight').removeClass('highlight');
$this.closest('.q').addClass('highlight');
});
});
HTML
<div class="box"> 1st set
<div class="q">
<input type="radio" id="1" name="11" />
<label for 1>a</label>
</div>
<div class="q">
<input type="radio" id="2" name="11" />
<label for 2>b</label>
</div>
</div>
<div class="box">
<hr> 2nd set
<div class="q">
<input type="radio" id="3" name="22" />
<label for 3>a</label>
</div>
<div class="q">
<input type="radio" id="4" name="22" />
<label for 4>b</label>
</div>
</div>
Upvotes: 2