-1

I have 4 checkboxes and I want to limit the selection up to 3. Did my google search, found a working one:

http://jsfiddle.net/vVxM2/

This is my code:

<html>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        var limit = 3;
        $('input.ko_chk').on('change', function(evt) {
           if($(this).siblings(':checked').length >= limit) {
               this.checked = false;
           }
        });
    </script>
    <body>
        <input type="checkbox" class="ko_chk" name="first" value="1"><br>
        <input type="checkbox" class="ko_chk" name="second" value="2"><br>
        <input type="checkbox" class="ko_chk" name="third" value="3"><br>
        <input type="checkbox" class="ko_chk" name="fourth" value="4">
    </body>
</html>

Still...

enter image description here

So, how is my code different?

fishmong3r
  • 1,354
  • 1
  • 21
  • 46
  • 1
    Your code already works as intended if you include a jQuery tag. http://jsfiddle.net/nph/vVxM2/2492/ – Nathan Hinchey May 23 '18 at 17:33
  • 2
    Your code doesn't run at all. You have to have a separate script tag for jQuery and your own code. – JJJ May 23 '18 at 17:34
  • 2
    After you've fixed that, the problem is this: [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – JJJ May 23 '18 at 17:34
  • I completely missed that the script was inside the jquery script include, haha. man... – Taplar May 23 '18 at 17:35

1 Answers1

0

You just need to make the jQuery script its own tag, and put your script after the tags you intend to select.

<input type="checkbox" class="ko_chk" name="first" value="1"><br>
<input type="checkbox" class="ko_chk" name="second" value="2"><br>
<input type="checkbox" class="ko_chk" name="third" value="3"><br>
<input type="checkbox" class="ko_chk" name="fourth" value="4">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  var limit = 3;
  $('input.ko_chk').on('change', function(evt) {
    if ($(this).siblings(':checked').length >= limit) {
      this.checked = false;
    }
  });
</script>
Taplar
  • 24,246
  • 4
  • 18
  • 33
Nathan Hinchey
  • 1,090
  • 7
  • 30
  • 2
    At the time `$('input.ko_chk')` is executed, the DOM is not ready, so the selector does not fine any elements. – t.niese May 23 '18 at 17:37
  • @t.niese -- good point, fixed. Also, I converted this to Community Wiki. Please feel free to fix anything else. – Nathan Hinchey May 23 '18 at 17:42