Reputation: 109
The code in the snippet disables all checked states when the #checkall
is checked, but I want to revert back to the original checked
state of each checkbox when #checkall
is unchecked again.
The desired UX is to simulate turning off notifications.
$(document).ready(function() {
$('#checkall').click(function() {
var checked = $(this).prop('checked');
$('#checkboxes').find('input:checkbox').prop('checked', false);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkall" />
<label for="checkall">Disable</label>
<br/>
<br/>
<div id="checkboxes">
<input type="checkbox" checked/>
<input type="checkbox" />
<input type="checkbox" checked/>
<input type="checkbox" checked/>
<input type="checkbox" />
<input type="checkbox" checked/>
<input type="checkbox" />
</div>
Upvotes: 0
Views: 48
Reputation: 1479
The original checked state is stored in .attr('checked'):
$('#checkboxes').find('input:checkbox').each(function(x) {
$(this).prop('checked', $(this).attr('checked') == 'checked' ? true : false)
})
Upvotes: 0
Reputation: 4309
Another way to do it.
It's generally better to use ".on('change',..." rather than binding directly to the "click" event.
$(document).ready(function () {
$('#checkall').on("change", function () {
if (!$(this).prop('checked')) {
$('#checkboxes input[type=checkbox]').each(function (index, elem) {
var input = $(elem);
input.prop('checked', input.data('was-checked'));
});
}
else {
$('#checkboxes input[type=checkbox]').each(function (index, elem) {
var input = $(elem);
input.data('was-checked',input.prop('checked'));
input.prop('checked', false);
});
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkall" />
<label for="checkall">Disable</label>
<br/>
<br/>
<div id="checkboxes">
<input type="checkbox" checked/>
<input type="checkbox" />
<input type="checkbox" checked/>
<input type="checkbox" checked/>
<input type="checkbox" />
<input type="checkbox" checked/>
<input type="checkbox" />
</div>
Upvotes: 2
Reputation: 15555
$(document).ready(function() {
$('#checkall').click(function() {
var checked = $(this).prop('checked');
$('#checkboxes').find('input:checkbox').prop('checked', false);
$('#checkboxes').find('input:checkbox[data-checked="checked"]').prop('checked', !checked);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkall" />
<label for="checkall">Disable</label>
<br/>
<br/>
<div id="checkboxes">
<input type="checkbox" data-checked="checked" checked/>
<input type="checkbox" />
<input type="checkbox" data-checked="checked" checked/>
<input type="checkbox" data-checked="checked" checked/>
<input type="checkbox" />
<input type="checkbox" data-checked="checked" checked/>
<input type="checkbox" />
</div>
Upvotes: 1