0

I have 2 checkboxes as below. The 2nd one should be clickable only if the 1st one checked. This I managed to do.

But if the first one is unchecked, the second one should be disabled and unchecked as well.

$(document).ready(function() {
  var ckbox = $('#optin');

  $('input').on('click', function() {
    if (ckbox.is(':checked')) {
      $('#tc').removeAttr('disabled'); //enable input

    } else {
      $('#tc').prop('checked', false); //remove check
      $('#tc').removeAttr('checked'); //disable input

    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="optin" id="optin" class="required">
<label for="optin"> Checkbox1 </label>

<input type="checkbox" name="tc" id="tc" class="" disabled="disabled">
<label for="tc"> Checkbox2  </label>

0

2 Answers 2

1

I'd do it like this:

$(document).ready(function() {
  $('input').on('click', function() {
    $('#tc').prop({
      'checked': $('#optin').is(':checked'),
      'disabled': !$('#optin').is(':checked')
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="optin" id="optin" class="required">
<label for="optin"> Checkbox1 </label>

<input type="checkbox" name="tc" id="tc" class="" disabled="disabled">
<label for="tc"> Checkbox2  </label>

Sign up to request clarification or add additional context in comments.

2 Comments

It should be possible to only check checkbox1
I don't understand what you mean by that. Do you mean like jsfiddle.net/q01p2gf1?
0

In the else you're trying to remove the checked attribute. Instead set the disabled property to true.

$(document).ready(function() {
  var ckbox = $('#optin');

  $('input').on('click', function() {
    if (ckbox.is(':checked')) {
      $('#tc').removeAttr('disabled'); //enable input

    } else {
      $('#tc').prop('checked', false); //remove check
      $('#tc').prop('disabled', true); //disable input

    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="optin" id="optin" class="required">
<label for="optin"> Checkbox1 </label>

<input type="checkbox" name="tc" id="tc" class="" disabled="disabled">
<label for="tc"> Checkbox2  </label>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.