user3371049 user3371049 - 2 months ago 12
jQuery Question

Check if one of the radio buttons within a div is checked

I found here this script that does almost what I need (find out if one radio button within a div is checked), although, it alerts me for each radio button, I just need one alert if one of them is checked.

Background info:
If one is checked I will show the next div. If not the div won't show. On top in my system, a click on a checked radio button will uncheck it, then the showed div will be hidden.

My code:

<div class="divtop">
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<div>


Here is the script:

$('.divtop input:radio').live('click', function(event) {
var div = $("div.divtop");
var radiobuttons = div.find("input[type='radio']");
for (var i = 0; i < radiobuttons.length; i++) {
if (radiobuttons[i].type === 'radio' && radiobuttons[i].checked) {
alert ('on') // action
} else {
alert ('off') // action
}} });


How can I adapt this script to get only one alert when one of the radio button is checked?

The function must be generic (no use of radio button names) because it will apply in different situations with different groups of radio buttons.

Answer

You can check if first div has checked radio, then show another div.

$(document).ready(function(){
    $('.divtop > input:radio').change(function(){
      if($(this).is(":checked"))
      {
        $('.divMiddle').removeClass('hide');  
      }
    });
});
.hide
{
  display: none;  
} 
.show
{
  display: block;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divtop">
    <input type="radio" name="r1" value="v1" />ONE
    <input type="radio" name="r1" value="v2" />TWO
    <input type="radio" name="r1" value="v3" />THREE
<div>
<div class="divMiddle hide">
    <input type="radio" name="r11" value="v11" /> ONE
    <input type="radio" name="r11" value="v22" /> TWO
    <input type="radio" name="r11" value="v33" /> THREE
</div>

Comments