Reputation: 1
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>
Upvotes: 0
Views: 1241
Reputation: 64536
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>
Upvotes: 0
Reputation: 208002
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>
Upvotes: 1