Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There were a couple of things wrong. Lets give the good version first. </p> <p>I also put up a demo at: <a href="http://jsbin.com/ajimi" rel="nofollow noreferrer">http://jsbin.com/ajimi</a></p> <pre><code>function verify_selected(currentCheckbox) { var count = 0; var selected_check_boxes = []; // this will be fine... var check_boxes []; var inputs = document.getElementsByTagName("input"); for( var i in inputs ) { if( inputs[i].type == "checkbox" ) check_boxes.push( inputs[i] ); } // get all "checked" for( var i in check_boxes ) { if( check_boxes[i].checked ) { count += 1; } } if( currentCheckbox.checked &amp;&amp; (count == 4)) { for( var i in check_boxes ) if( !check_boxes[i].checked ) check_boxes[i].disabled = true; } else { for( var i in check_boxes ) check_boxes[i].disabled = false; } } </code></pre> <p>In the original version, you've got a piece of code which looked like:</p> <pre><code>if (count &lt; 4) { if (count == 4) { </code></pre> <p>Not gonna happen. So, that was corrected. </p> <p>As you saw also in another answer, we changed the function to take out looking for an ID. Rather than figuring out the ID in some separate function (I assume you're tracking the "last clicked" by some other function which occurs), just use the this modifier to pass it into the function.</p> <p>Alright, last but not least, what this would look like in jQuery. Hopefully this will help a little as to understanding how it works and why it's worth using:</p> <p>(see example: <a href="http://jsbin.com/ihone" rel="nofollow noreferrer">http://jsbin.com/ihone</a>)</p> <pre><code>function limitSelected(e) { // get all of your checkboxes var checkBoxes = $(e.currentTarget).parent().children().filter('input:checkbox'); // get the number of checkboxes checked, if 4, we'll disable var disableCheckBoxes = (checkBoxes.filter(':checked').length == 4); // enable checkboxes if we have &lt; 4, disable if 4 checkBoxes.filter(':not(:checked)').each(function() { this.disabled = disableCheckBoxes; }); } // when the document is ready, setup checkboxes to limit selection count // if you have a particular div in which these checkboxes reside, you should // change the selector ("input:checkbox"), to ("#yourDiv input:checkbox") $(function() { $('input:checkbox').click(limitSelected); }); </code></pre> <p>The other thing I will note about this version is that it works on the group of checkboxes within a div, as opposed to your version which will pick up checkboxes on the entire page. (which is limiting.</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