Stumbler
Stumbler

Reputation: 2146

Counting checkboxes of element

Okay, so I have some javascript code that is meant to do two things: tick checkboxes that have identical values (if checkbox with value "3" is checked, then any other with value "3" should also be checked). It is also meant to count how many checked boxes there are in total afterwards. This works perfectly.

  $(".chkbox").on('change',function() {
                    var max_number =8;                  

                    var val = ($(this).val();
                    if ($(this).is(":checked")) {

                      $(":checkbox[value='" + val + "']").prop("checked", true);
                    } else {
                      $(":checkbox[value='" + val + "']").prop("checked", false);
                    }
                    var count = $("[type='checkbox']:checked").length;
                    if (count>=max_number){
                        alert("too many chosen!");
                    }
                    alert (count);
                  });

However, there are some checkboxes in the html which are not relevant, and are being counted erroneously. As such I have given the section which contains the relevant checkboxes the id of "test" and rewritten the javascript:

 $(".chkbox").on('change', function() {
   var max_number = 8;

   var val = ($(this).children("#test")).val();
   if (($(this).children("#test")).is(":checked")) {

     $(":checkbox[value='" + val + "']").prop("checked", true);
   } else {
     $(":checkbox[value='" + val + "']").prop("checked", false);
   }
   var count = $("[type='checkbox']:checked").length;
   if (count >= max_number) {
     alert("too many chosen!");
   }
   alert(count);
 });
<section id="test">
  <table style="display:inline-block;" border="1">
    <tr id="9">
      <td>9</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
      </td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" /><a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
      </td>
    </tr>
    <tr id="10">
      <td>10</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
      </td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" /><a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
      </td>
    </tr>
    <tr id="11">
      <td>11</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" /><a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
      </td>
      <td>&nbsp;</td>
    </tr>
    <tr id="12">
      <td>12</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" /><a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
      </td>
      <td>&nbsp;</td>
    </tr>
    <td>18</td>
    <td style="background-color:#">
      <input type="checkbox" class="chkbox" name="selection[array_name][]" title="2" value="2" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
    </td>
    <td>&nbsp;</td>
    </tr>
  </table>
</section>

This correctly counts the number of checkboxes - but it no longer ticks all checkboxes with the same value in test! How can I fix this?

Upvotes: 0

Views: 109

Answers (2)

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

// binding the anonymous function of the on() method as the
// event-handler of the <input> elements of type=checkbox, and
// class of 'chkbox':
$('input[type=checkbox].chkbox').on('change', function() {
  var maxNumber = 8,

      // caching a reference to the changed element:
      changed = this,

      // caching a reference to the changed element's value:
      value = changed.value,

      // caching the collection of relevant checkboxes:
      checkboxes = $('input[type=checkbox].chkbox');

  // updating the checked property of each of the checkboxes:
  checkboxes.prop('checked', function () {

    // returning true (and therefore setting the
    // checked property to true) if the current
    // <input> element's value is equal to the value
    // of the changed <input> AND if the changed element
    // is checked (thereby allowing us to uncheck the
    // checkboxes); if the assessment evaluates to false
    // the checked property is set to false:
    return this.value === value && changed.checked;
  });

  // setting the text of the '#result' element - adjust
  // to taste, but I wasn't sure where you wanted the
  // relevant number to be shown:
  $('#result').text(function () {

    // here we filter the checkboxes collection to only
    // those that are checked (using the CSS ':checked'
    // selector:
    return checkboxes.filter(':checked').length + ' of ' + checkboxes.length + ' checkboxes checked';
  });

}).change();

$('input[type=checkbox].chkbox').on('change', function() {
  var maxNumber = 8,
    changed = this,
    value = changed.value,
    checkboxes = $('input[type=checkbox].chkbox');

  checkboxes.prop('checked', function() {
    return this.value === value && changed.checked;
  });

  $('#result').text(function() {
    return checkboxes.filter(':checked').length + ' of ' + checkboxes.length + ' checkboxes checked';
  });

}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="test">
  <table style="display:inline-block;" border="1">
    <tr id="9">
      <td>9</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" />
        <a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
      </td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" />
        <a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
      </td>
    </tr>
    <tr id="10">
      <td>10</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" />
        <a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
      </td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" />
        <a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
      </td>
    </tr>
    <tr id="11">
      <td>11</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" />
        <a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
      </td>
      <td>&nbsp;</td>
    </tr>
    <tr id="12">
      <td>12</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" />
        <a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
      </td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>18</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="2" value="2" />
        <a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
      </td>
      <td>&nbsp;</td>
    </tr>
  </table>
</section>
<div id="result"></div>

References:

Upvotes: 1

dangor
dangor

Reputation: 465

On line 3 of your JS, you're calling

var val = ($(this).children("test")).val();

First of all, you can't just use ("test"), since that's not a valid selector (you're missing the "#").

Furthermore, $(this) is referring to the changed input element, in your case a checkbox, which has no children.

So, if you want the value of the checkbox, you definitely want to call .val() on $(this):

var val = $(this).val();

If you wanted to target only the checkboxes with the "test" id, you could do so when you set your event:

$("#test .chkbox").on('change'....

.children() will traverse down the DOM, looking for elements which match the selector. If you wanted to traverse up the DOM, I guess you could use .closest(). You would then check if the target element has a parent with an id of #test, and afterwards do your thing:

if ($(this).closest("#test").length > 0) {
    var val = $(this).val();
    // other stuff...
}

Upvotes: 1

Related Questions