Claudio Delgado
Claudio Delgado

Reputation: 2349

jQuery to only show labels of checked checkboxes and hide the unchecked ones

I have this setup:

<style>.selectit{display:none;}</style>
<div id="foo">
<label class="selectit">
<input type="checkbox" name="one" id="one" checked>
One
</label>
<label class="selectit">
<input type="checkbox" name="two" id="two">
Two
</label>
<label class="selectit">
<input type="checkbox" name="three" id="three" checked>
Three
</label>
</div>

I only want to display the Label tags for the checked inputs and hide the labels for others.

something like show() for the checked inputs labels and hide() for the unchecked ones.

example of working code:

<style>.selectit{display:none;}</style>
<div id="foo">
<label class="selectit" style="display:block">
<input type="checkbox" name="one" id="one" checked>
One
</label>
<label class="selectit">
<input type="checkbox" name="two" id="two">
Two
</label>
<label class="selectit" style="display:block">
<input type="checkbox" name="three" id="three" checked>
Three
</label>
</div>

or maybe perhaps, make a new div and only show the text of the checked labels in that div.

<style>.selectit{display:none;}</style>
<div id="foo">
<label class="selectit">
<input type="checkbox" name="one" id="one" checked>
One
</label>
<label class="selectit">
<input type="checkbox" name="two" id="two">
Two
</label>
<label class="selectit">
<input type="checkbox" name="three" id="three" checked>
Three
</label>
</div>
<div id="output">One - Three</div>

is this even possible? or do I need to do this by appending a div that searches the whole checkboxes? Any help is appreciated because I've exhausted all my options already and I'm out of ideas. Thank you in advance.

Upvotes: 2

Views: 1810

Answers (2)

jAndy
jAndy

Reputation: 236022

Disclaimer: This answer is just based on your title question


I'd go with pure CSS for that. Like

label {
    display: none;
} 

input:checked + label {
    display: block;
} 

You would just need to adjust your markup a little.

Example: http://jsfiddle.net/ZpmGd/

Upvotes: 2

Ram
Ram

Reputation: 144689

You can filter checked checkboxes using filter method.

$('#foo input[type=checkbox]').filter(function(){
      return this.checked;
}).prev('label').show();

Upvotes: 3

Related Questions