Kyle Underhill
Kyle Underhill

Reputation: 109

One checkbox un-checks the other

I'm trying to uncheck the checkbox that isn't selected to simulate a radio because I have a scenario where checkboxes must be used. However the code doesn't work properly for the second button.

Note I need to preserve the find because the checkboxes are in different locations at site.

$("input").change(function() {
  var t = $(this).closest(".item");
  var btnOne = t.find("#one");
  var btnTwo = t.find("#two");
  if (btnOne.is(":checked")) {
    btnTwo.prop("checked", false);
  } else if (btnTwo.is(":checked")) {
    btnOne.prop("checked", false);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
  <input type="checkbox" id="one">
  <input type="checkbox" id="two">
</div>

Upvotes: 0

Views: 30

Answers (1)

Christian Carrillo
Christian Carrillo

Reputation: 2761

You could try this:

$("input").change(function() {
  var t = $(this).closest(".item");
  var btnOne = t.find("#one");
  var btnTwo = t.find("#two");

  if (btnOne.is(":checked") && $(this).attr("id") === 'two') {
    btnOne.prop("checked", false);
    btnTwo.prop("checked", true);
  }
  if (btnTwo.is(":checked") && $(this).attr("id") === 'one') {
    btnTwo.prop("checked", false);
    btnOne.prop("checked", true);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
  <input type="checkbox" id="one">
  <input type="checkbox" id="two">
</div>

Upvotes: 1

Related Questions