Reputation: 844
Is there a way to hide checkboxes that aren't checked? I have three checkboxes and I'm looking for a way to hide the ones that aren't checked. The code I have now hides all checkboxes and I'm trying to hide the ones that aren't checked.
This is my code:
$('input[type=checkbox]').each(function ()
{
//Check if the box is checked
var x = $(this).is(':checked');
//if checkbox is NOT checked
if(x === false)
{
//Hide the choice
$(this).parent().hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="testing" value="B">A</label><br />
<input type="checkbox" name="testing" value="I">B</label><br />
<input type="checkbox" name="testing" value="A">C</label><br />
Upvotes: 2
Views: 708
Reputation: 360
@5alidshammout is right. You need a change event and if you want to show all again on uncheck of that box you can simply use if statement. Also starting tags for <label>
were missing in your code too.
$('input[type=checkbox]').on('change', function() {
if ($(this).is(':checked')) {
$('input[type=checkbox]').each(function() {
//Check if the box is checked
var x = $(this).is(':checked');
//if checkbox is NOT checked
if(x === false) {
//Hide the choice
$(this).parent().hide();
}
});
} else {
$('input[type=checkbox]').parent().show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="checkbox" name="testing" value="B">A</label><br />
<label><input type="checkbox" name="testing" value="I">B</label><br />
<label><input type="checkbox" name="testing" value="A">C</label><br />
Upvotes: 1
Reputation: 995
You can try this,
// Hide the choice
$(this).hide();
Instead of,
// Hide the choice
$(this).parent().hide();
Upvotes: 0
Reputation: 329
You can check if a checkbox is checked or not with this:
if (document.getElementById('testing').checked) {
//something
}
Upvotes: 0