Joe Cook
Joe Cook

Reputation: 71

Uncheck radio button when another radio button is clicked in Jquery

I have two pairs of radio buttons. When you click the first of the first pair it shows the second pair which are hidden by default. no problem there. Now once I click the first radio button the second set are now required. If I click to hide the second set and the click again to show the second set I cannot get the check to go away.

$("input[name='FirstSetName']").on("change", function() {
  //answer is yes
  if ($(this).val() === "true") {
    $("#ShowSecondSet").show();
    $("#SecondsetName").prop("checked", false);
    $("#SecondsetName").rules("add", "required");
  }
  //answer is No
  else if ($(this).val() === "false") {
    alert("else");
    $("#SecondsetName").prop("checked", false);
    $("#SecondsetName").rules("remove", "required");
    $("#HideSecondSet").hide();
  }
});

I have tried to use attr and prop nothing works.

Any thoughts?

Upvotes: 0

Views: 39

Answers (1)

Karan
Karan

Reputation: 12619

You should be using $("input[name='SecondSetName']").prop("checked", false);.

Also use $("input[name='SecondSetName']").show(); and $("input[name='SecondSetName']").hide(); instead of $("#ShowSecondSet").show(); & $("#HideSecondSet").hide();.

Uncomment $("#SecondsetName").rules("add", "required"); I comment it because I haven't applied and used rules.

You have not shared your html so I have added it based on javascript code.

Try it below.

$("input[name='FirstSetName']").on("change", function() {
  //answer is yes
  if ($(this).val() === "true") {
    $("input[name='SecondSetName']").show();
    $("input[name='SecondSetName']").prop("checked", false);
    // $("#SecondsetName").rules("add", "required");
  }
  //answer is No
  else if ($(this).val() === "false") {
    $("input[name='SecondSetName']").prop("checked", false);
    // $("#SecondsetName").rules("remove", "required");
    $("input[name='SecondSetName']").hide();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
true<input type='radio' name='FirstSetName' value='true' />
false<input type='radio' name='FirstSetName' value='false' />
<div>
  second 1<input type='radio' name='SecondSetName' value='2.1' style='display:none;' />
  second 2<input type='radio' name='SecondSetName' value='2.2' style='display:none;' />
</div>

Upvotes: 1

Related Questions