jquery radio button for multiple groups
I am u开发者_StackOverflowsing jquery for styling a radio button, but it doesn't work if a have multiple groups - meaning that only one element is styled at once right now.
I have in the code:
<script type="text/javascript">
$(document).ready(function(){
$(".RadioClass").change(function(){
if($(this).is(":checked")){
$(".RadioSelected:not(:checked)").removeClass("RadioSelected");
$(this).next("label").addClass("RadioSelected");
}
});
});
</script>
and in the html:
<input id="Radio1" type="radio" class="RadioClass" name="group1" >
<label id="Label1" for="Radio1" class="RadioLabelClass">Radio 1</label>
<input id="Radio2" type="radio" class="RadioClass" name="group2"/>
<label id="Label2" for="Radio2" class="RadioLabelClass">Radio 2</label>
<input id="Radio3" type="radio" class="RadioClass" name="group1"/>
<label id="Label3" for="Radio3" class="RadioLabelClass">Radio 3</label>
Well, where I have group2
for example, the radio image doesn't change as it should, accordingly to jquery.
Any idea about how can I make it work for different group names?
not very reliable works
$(".RadioClass").change(function(){ ...
better to replace
$(".RadioClass").click(function(){ ...
Try this,
$(".RadioClass").change(function(){
if($(this).is(":checked"))
{
var groupName = $(this).attr("name");
$(".RadioClass").each(function(idx)
{
if($(this).attr("name") == groupName)
{
$(this).next("label").removeClass("RadioSelected");
}
});
$(this).next("label").addClass("RadioSelected");
}
});
Edit: I also realised it's probably quicker to just select the elements by name.
$(".RadioClass").change(function(){
if($(this).is(":checked"))
{
var groupName = $(this).attr("name");
$("[name='"+groupName+"']").next("label").removeClass("RadioSelected");
$(this).next("label").addClass("RadioSelected");
}
});
精彩评论