Reputation: 459
I am having some trouble with the styling of a checked radio button, my code generaly works, except for when there is a DEFAULT checked radio button, then the styling no longer works until I check a different radio button. My question is how can I have the same styling applied to a radio button when checked by default and is it possible to do it with CSS only?
Here is my code:
HTML
<div class="accessOptions">
<div class="option">
<input type='radio' id="1" name='11' checked='checked' class="highlight"/>
<label for 1>Open to Anyone</label>
</div>
<div class="option">
<input type="radio" id="2" name="11" />
<label for 2>Only to Allowed Senders</label>
</div>
</div>
CSS:
.highlight {
background: #5479ab;
}
jquery:
$(document).ready(function(){
$('input:radio').change(function(){
var $this = $(this);
$this.closest('.accessOptions').find('div.highlight').removeClass('highlight');
$this.closest('.option').addClass('highlight');
});
});
link to jsfiddle: http://jsfiddle.net/priswiz/BMB9R/
Upvotes: 1
Views: 1548
Reputation: 10190
The easiest way would be to simply add the class highlight
to the div
that contains the radio that is selected by default. Since your JS removes the class once another radio is selected, this should work just fine. Here is a fiddle: http://jsfiddle.net/w4UDz/1/
<div class="accessOptions">
<div class="option highlight">
<input type='radio' id="1" name='11' checked='checked'/>
<label for="1">Open to Anyone</label>
</div>
<div class="option">
<input type="radio" id="2" name="11" />
<label for="2">Only to Allowed Senders</label>
</div>
</div>
Upvotes: 3
Reputation: 8054
You can use CSS3's :checked
selector.
.highlight:checked {
background: #5479ab;
}
No scripting required.
Edit:
Given the details I didn't catch during my first answer, here's how you can apply the styles to the parent div
of the radio
in question:
$(document).ready(function(){
$('input:radio.highlight:checked').parent(".option").addClass("highlight");
$('input:radio').change(function(){
var $this = $(this);
$this.closest('.accessOptions').find('div.highlight').removeClass('highlight');
$this.closest('.option').addClass('highlight');
});
});
Upvotes: 4
Reputation: 196236
You need to run the code on the pre-checked element
so add .filter(':checked').change();
to your code..
$(document).ready(function(){
$('input:radio').change(function(){
var $this = $(this);
$this.closest('.accessOptions').find('div.highlight').removeClass('highlight');
$this.closest('.option').addClass('highlight');
}).filter(':checked').change();
});
The other issue is that in your HTML you applied the class to the wrong element..
If you are to mimic what your code does, you should add the .highlight
class to the div
and not the input
like this
<div class="option highlight">
<input type='radio' id="1" name='11' checked='checked' />
<label for 1>Open to Anyone</label>
</div>
at least that is what your code does..
Upvotes: 1