Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your HTML is invalid. <code>id</code> values must be <strong>unique</strong> within a document (<a href="http://www.w3.org/TR/html5/elements.html#concept-id" rel="nofollow">reference</a>).</p> <p>That said, ignoring the <code>id</code> values, you could use this (<a href="http://jsbin.com/odome3" rel="nofollow">live example</a>):</p> <pre><code>$(':checkbox[name^=correct]').each(function() { switch (this.value) { case "0": case "3": case "4": this.checked = true; break; } }); </code></pre> <p>That uses a CSS3 substring selector (jQuery supports nearly all of CSS3) on the <code>name</code> attribute to select any checkbox with a name starting with <code>correct</code>, and then uses jQuery's <a href="http://api.jquery.com/each/" rel="nofollow"><code>each</code></a> to loop through them. Then we set the <code>checked</code> property on the ones with the desired <code>value</code>.</p> <p>You could also do it with a longer selector and without the loop (<a href="http://jsbin.com/odome3/2" rel="nofollow">live example</a>):</p> <pre><code>$(':checkbox[name^=correct][value=0], :checkbox[name^=correct][value=3], :checkbox[name^=correct][value=4]').attr('checked', true); </code></pre> <p><strong>Update</strong>: Re-reading your question, it looks like you might need to do this more dynamically:</p> <pre><code>&lt;script type='text/javascript'&gt; (function() { var boxes = $(); // Assumes jQuery 1.4 or higher &lt;?php foreach($toCheck as $checkMe) { ?&gt; echo "boxes.add(':checkbox[name=^=correct][value=" . $toCheck . "]');"; &lt;?php }; ?&gt; boxes.attr('checked', true); })(); &lt;/script&gt; </code></pre> <p>...which would generate:</p> <pre><code>&lt;script type='text/javascript'&gt; (function() { var boxes = $(); // Assumes jQuery 1.4 or higher boxes.add(':checkbox[name=^=correct][value=0]'); boxes.add(':checkbox[name=^=correct][value=3]'); boxes.add(':checkbox[name=^=correct][value=4]'); boxes.attr('checked', true); })(); &lt;/script&gt; </code></pre> <p>...which would check the relevant boxes. But it wouldn't be very efficient (all of that document traversal), better off using PHP to combine the values into a selector or <code>switch</code> as shown above.</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