Javascript Checkboxes + dedicated variable creation

Solution 1:

Here is a code that will trigger an event when the check box with class checkbox is changed:

<div>
  <input type="checkbox" class="checkbox" name="option1">
  <label for="option1">option1</label>
</div>
<div>
  <input type="checkbox" class="checkbox" name="option2">
  <label for="option2">option2</label>
</div>


<script type="text/javascript">

 document.querySelectorAll('.checkbox').forEach(item => {
   item.addEventListener('change', event => {

     // lets get name that we can find out which one has been changed
     let name = event.target.getAttribute("name");
      if(event.target.checked){
        console.log(`${name} was unchecked and now is checked`);
      }else{
        console.log(`${name} was checked and now is unchecked`);
      }
      


   })
 })

</script>

so you can have as many checkboxes as you want with class checkbox

During our discuss in the comments you want to save some commands, so these may help you:

<div>
  <input type="checkbox" data-command="vlan1=command1" class="checkbox" name="option1">
  <label for="option1">option1</label>
</div>
<div>
  <input type="checkbox" data-command="vlan4=command2" class="checkbox" name="option2">
  <label for="option2">option2</label>
</div>

<button type="button" id="save">save</button>


<script type="text/javascript">


    let commands = [];
   document.getElementById("save").addEventListener("click" , event => {

        document.querySelectorAll('.checkbox').forEach(item => {

            
            if(item.checked){
                let name = item.getAttribute("name");
                //do some thing here
                commands['comamnd_' + name] = item.getAttribute("data-command");
            }

        });

   });
 

</script>

Whenever the submit button is clicked you have a loop throw all the inputs and save commands in an array.

After that, you can use the element of array like commands.comamnd_option1 or just loop throw the array.