Search code examples
javascriptjquerycheckboxchecked

Check if value of selected checkboxes are in data-attribute


I need to find out if the values of selected checkboxes can be found in the data-attribute of a given div.

Only if ALL the checkboxes with the values found in the data-attribute are checked, the result should be TRUE. If one or more checkboxes with values found in the data-attribute is unchecked, the result should be FALSE.

Examples:

<div id="towns" data-attribute="FRA, BER, HAM">...</div>

Selected Checkboxes: FRA, BER => Result: false

Selected Checkboxes: BER, HAM, MUC => Result: false

Selected Checkboxes: FRA, BER, HAM => Result: true

Selected Checkboxes: FRA, BER, HAM, MUC => Result: true

$("input[type=checkbox]:checked").each(function() {

  console.log($("#testdiv").data("town").split(",").indexOf($(this).val()) > -1);
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<input type="checkbox" value="FRA" checked />
<input type="checkbox" value="BER" checked />
<input type="checkbox" value="HAM" />
<input type="checkbox" value="MUC" />

<div id="testdiv" data-town="FRA, BER, HAM">
  Lorem ipsum
</div>

Currently I only know to the result of one checkbox value. But I need to have a result of false if one of the towns presented in the data-attribute is missing.


Solution

  • You can add a for loop that goes through every value in the data-town and checks if they are checked, rather than loop through every checkbox that is checked.

    function testChecked() {
      let arr = $("#testdiv").data("town").split(",");
      
      for (let i = 0; i < arr.length; i++) {
        if (!$("input[value=" + arr[i] + "]").is(":checked")) return false;
      }
      
      return true;
    }
    
    console.log(testChecked());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <input type="checkbox" value="FRA" checked />
    <input type="checkbox" value="BER" checked />
    <input type="checkbox" value="HAM" checked />
    <input type="checkbox" value="MUC" />
    
    <div id="testdiv" data-town="FRA,BER,HAM">
      Lorem ipsum
    </div>