Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The answer is: it depends on your DOM. If your <code>&lt;a&gt;</code> elements are inside the form, you could use <a href="http://api.jquery.com/closest/" rel="nofollow">$.closest()</a>:</p> <pre><code>function toggleCheck(state) { $(this) .closest("form") .find("input[type=checkbox]") .prop('checked', state); } </code></pre> <p>I slightly altered your code to increase readability, performance (see the additional notes regarding the <a href="http://api.jquery.com/checkbox-selector/" rel="nofollow">:checkbox selector</a>) and be more "jQuery"-like.</p> <p>[edit] After reading the comments I rewrote the function, still on the assumption that the <code>&lt;a&gt;</code> elements are inside the <code>&lt;form&gt;</code>, this time also with a working <a href="http://jsfiddle.net/Sw5jB/1/" rel="nofollow">jsFiddle</a>:</p> <pre><code>function toggleCheck(state) { $(document).find(event.target) .closest("form") .find("input[type=checkbox]") .prop('checked', state); } </code></pre> <p>[edit2] And for the sake of completness regarding my comment about the order of the elements (<a href="http://jsfiddle.net/Sw5jB/4/" rel="nofollow">jsFiddle</a>):</p> <pre><code>function toggleCheck(state) { var pos = $(document).find(event.target.localName + "." + event.target.className).index(event.target); var $form = $($(document).find("form").get(Math.floor(pos/2))); $form .find("input[type=checkbox]") .prop('checked', state) } </code></pre> <p>[edit3] The last edit, I promise. This time I ignore the default callback and do <a href="http://jsfiddle.net/Sw5jB/5/" rel="nofollow">my own thing</a>:</p> <pre><code>function toggleCheck(state) { // either write the s tate now in a variable for // the next callback } $(document).on("click", "a.btn", function(e) { var $ele = $(this); // or do some string exploration var toggle = $ele.attr("onclick").indexOf("true") &gt; -1; var pos = $(document).find("a.btn").index($ele); var $form = $($(document).find("form").get(Math.floor(pos/2))); $form .find("input[type=checkbox]") .prop('checked', toggle); }); </code></pre> <p>Works without having to touch anything. But I wouldn't want to use this. ;-)</p>
 

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