Sergi
Sergi

Reputation: 1240

Check or uncheck a checkbox if another one is checked with jQuery

I have a basic if/else statement that checks if two inputs are checked, if they are, a third checkbox state of "disabled" turns to false and it can be checked. I would like that once checked, if the other checkboxes are unchecked, this one would go unchecked again, but it just gets disabled while mantaining the check.

My code:

$("#cvLinkedInAssessmentCheck :input, #rolePlayingTalentCheck :input").change(function(){
        if( $(this).is(':checked') ){
            $("#minutosTalentoCheck :input").attr("disabled", false);
            $("#minutosTalentoCheck").css("opacity", "1");
        } else {
            $("#minutosTalentoCheck").prop('checked', false);
            $("#minutosTalentoCheck :input").attr("disabled", true);
            $("#minutosTalentoCheck").css("opacity", "0.3");

        }
    })

Basically, this line in the else statement is not working, I have also tried with "attr" instead with no luck:

$("#minutosTalentoCheck").prop('checked', false);

Upvotes: 0

Views: 1037

Answers (1)

Taplar
Taplar

Reputation: 24965

var $things = $("#cvLinkedInAssessmentCheck :input, #rolePlayingTalentCheck :input");

$things.on('change', function() {
  var $otherThing = $("#minutosTalentoCheck");
  
  //if either of the things are not checked, disable the other thing
  if ($things.not(':checked').length) {
    $otherThing
      .prop('checked', false)
      .attr("disabled", true)
      .css("opacity", "0.3");
  } else {
    $otherThing
      .prop("disabled", false)
      .css("opacity", "1");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cvLinkedInAssessmentCheck">
  <input type="checkbox"> Assessment
</div>
<div id="rolePlayingTalentCheck">
  <input type="checkbox"> Talent
</div>

<input type="checkbox" id="minutosTalentoCheck" disabled> Other thing

Upvotes: 1

Related Questions