Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>But that only handles one checkbox and doesn't work if I have more than one like above.</p> </blockquote> <p>That is because when using the id selector, jQuery only returns the first element it finds. Ids should be unique.</p> <p>As per <a href="http://api.jquery.com/id-selector/" rel="nofollow"><strong>documentation</strong></a> :</p> <blockquote> <p>Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.</p> </blockquote> <p>If you need to group elements you can either assign a class:</p> <pre><code>&lt;input type="checkbox" id="check1" class="checkbox-group1"&gt; &lt;input type="checkbox" id="check2" class="checkbox-group1"&gt; &lt;input type="checkbox" id="check3" class="checkbox-group1"&gt; </code></pre> <p>...attaching the click event selecting by class:</p> <pre><code>$('.checkbox-group1').click(function(){...}) </code></pre> <p>or you can use data attributes:</p> <pre><code>&lt;input type="checkbox" id="check1" data-group="checkbox-group1"&gt; &lt;input type="checkbox" id="check2" data-group="checkbox-group1"&gt; &lt;input type="checkbox" id="check3" data-group="checkbox-group1"&gt; </code></pre> <p>...attaching the click event selecting by data attribute:</p> <pre><code>$('input[data-group="checkbox-group1"]').click(function(){...}) </code></pre> <h3><a href="http://jsfiddle.net/3HFd2/" rel="nofollow">DEMO</a></h3>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload