mardi 30 juillet 2019

Checkbox Functionality with Two Series of Checkboxes

I'm currently developing a form that has two containers with checkboxes. There first is the master and then there's the secondary which corresponds to the master.

The first container's checkboxes contain a data attribute value such as: "One", "Three", "Ten", etc.

Upon clicking one of the master checkboxes (the onCheck function) it checks all the input data attribute values that have an input of "checked", and then proceeds to check every checkbox in the secondary container (which has an array of information in its data attribute) and if there's a match between any of the information, they get checked.

What I'm troubleshooting is when the user unchecks a master checkbox (which is the offCheck function), because if there's a master checkbox input that's checked and it corresponds to the data information in one of the secondary checkboxes, it shouldn't be unchecked. If there's no corresponding information, it gets unchecked.

Please let me know if you need clarification as this can be a bit confusing.

HTML:

<div class="master">
  <input type="checkbox"
    data-information="One"
  /> Primary Checkbox One

  <input type="checkbox"
    data-information="Two"
  /> Primary Checkbox Two

  <input type="checkbox"
    data-information="Three"
  /> Primary Checkbox Three
</div>

<div class="secondary">
  <input type="checkbox"
    data-information='["One", "Seven", "Ten"]'
  /> Secondary Checkbox One
  <input type="checkbox"
    data-information='["Two", "Three", "Ten"]'
  /> Secondary Checkbox One
</div>

jQuery / JavaScript:

function onCheck(){
    // Gather all information from checkboxes that are checked
  var informationOne = [];
  $(".master input:checkbox").each(function(){

        if($(this).is(":checked")){
        informationOne.push($(this).data("information"));
    }

  });

  $('.secondary input:checkbox').each(function(){

    var informationTwo = [];
        informationTwo = $(this).data("information");

    for(var i=0; i<informationTwo.length; i++){

      if($.inArray(informationTwo[i], informationOne) != -1){
        $(this).prop("checked", true);
      }

    }

  });
}

function offCheck(){
}


$(".master input:checkbox").change("checked", function(){
  if($(this).is(":checked")){
    onCheck();
  } else {
    offCheck();
  }
});




Aucun commentaire:

Enregistrer un commentaire