Sergelie
Sergelie

Reputation: 363

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.

Upvotes: 0

Views: 2625

Answers (2)

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

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>

Upvotes: 1

andrew
andrew

Reputation: 9583

In response to your comment on your post, it occurs to me you could achieve what you want with some simple css only:

[type="radio"], [type="radio"]:checked + .inner{
  display:block;
}

.inner{
  display:none
}
<div class="divtop">
    <input checked type="radio" name="r1" value="v1" />
    <div class="inner">ONE</div>
    <input type="radio" name="r1" value="v2" />
    <div class="inner">TWO</div>
    <input type="radio" name="r1" value="v3" />
    <div class="inner">THREE</div>
<div> 

Upvotes: 0

Related Questions