dimanche 11 juillet 2021

How to Push Checkbox Item into Array using Javascript

I have a checklist which I am pushing into an input field when the item is checked. When the item is unchecked, the item gets removed from the Input field. https://codepen.io/dragoncoderpanda/pen/abWmPgx

However, there is repetition of codes. For each Checkbox, I am having to create an individual function to push/pop the text.

How do I pass Arguments in my codes so that I don't have to write too many codes repetitively?

itemArray = [];
let inputField = document.querySelector('.inputField')
let itemOne = document.querySelector('#itemOne')

itemOne.addEventListener('click', alpha);

function alpha(){
  if(itemOne.checked == true){
    itemArray.push(itemOne.name);
    inputField.placeholder = itemArray;
    inputField.value = itemArray;
  } else{
    itemArray.pop(itemOne.name);
    inputField.placeholder = itemArray;
    inputField.value = itemArray;
  }
}

let itemTwo = document.querySelector('#itemTwo')
itemTwo.addEventListener('click', beta);
function beta(){
  if(itemTwo.checked == true){
    itemArray.push(itemTwo.name);
    inputField.placeholder = itemArray;
    inputField.value = itemArray;
  } else{
    itemArray.pop(itemTwo.name);
    inputField.placeholder = itemArray;
    inputField.value = itemArray;
  }
}



Aucun commentaire:

Enregistrer un commentaire