Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript how to loop key value pairs inside a function

I’m new to JavaScript.

I have 2 key and value pairs they are ids:

myselect->myoption
myselect2->myoption2

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  function checkboxStatusChanges() {
    var multiselect = document.getElementById("myselect");
    var multiselectOption = multiselect.getElementsByTagName('option')[0];
  
    var values = [];
    var checkboxes = document.getElementById("myoption");
    var checkedCheckboxes = checkboxes.querySelectorAll('input[type=checkbox]:checked');
  
    for (const item of checkedCheckboxes) {
      var checkboxValue = item.getAttribute('value');
      values.push(checkboxValue);
    }
  
    var dropdownValue = "Nothing is selected";
    if (values.length > 0) {
      dropdownValue = values.join(', ');
    }
  
    multiselectOption.innerText = dropdownValue;
  }

The code already used 1 of the pair values myselect->myoption document.getElementById("myselect") ,my question is ,how to code a loop inside the code ,so that both of the 2 pair values can be used in the code ?

>Solution :

You can use an array of objects to solve this. Define your pair value inside object.selectId and object.optionId and do forEach to apply the function for those objects like this:

function checkboxStatusChanges() {
    let targetIds = [{
            "selectId": "myselect",
            "optionId": "myoption"
        },
        {
            "selectId": "myselect2",
            "optionId": "myoption2"
        }
    ];
    targetIds.forEach(function(targetId) {
        var multiselect = document.getElementById(targetId.selectId);
        var multiselectOption = multiselect.getElementsByTagName('option')[0];

        var values = [];
        var checkboxes = document.getElementById(targetId.optionId);
        var checkedCheckboxes = checkboxes.querySelectorAll('input[type=checkbox]:checked');

        for (const item of checkedCheckboxes) {
            var checkboxValue = item.getAttribute('value');
            values.push(checkboxValue);
        }

        var dropdownValue = "Nothing is selected";
        if (values.length > 0) {
            dropdownValue = values.join(', ');
        }

        multiselectOption.innerText = dropdownValue;
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading