Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
How do I dynamically get the value of an element from an array of elements?

I have a form with 3 checkboxes. I'm trying to the value of whichever checkbox is clicked on. I'm able to get the value of a hardcoded checkbox index (checkbox[0] for example), but I can't get the value of checkbox[i] with vanilla JS.

document.addEventListener("DOMContentLoaded", function() {

  var checkboxes = document.getElementsByClassName('checkbox');
  var listType = document.getElementById('ListType');
  for (var i = 0; i < checkboxes.length; i++) {

    checkboxes[i].addEventListener('click', function() {

      var inputByIndex = checkboxes[0].value; //I can get the value of the first element, but I can't get the value of whichever checkbox is checked. checkbox[i] doesn't work.
      listType.classList.add(inputByIndex);
      var spanType = document.getElementById("type");
      spanType.innerText = inputByIndex;

    });
  }
});
input {
  margin: 20px;
}

#ListType.basiclist {
  color: red;
}

#ListType.accordionlist {
  color: blue;
}

#ListType.internalonly {
  color: pink;
}
<form id="ListTypes">
  <label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
  <label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
  <label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>

<div id="ListType">
  List Type: <span id="type"></span>
</div>

Fiddle

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use event.currentTarget to access the element on which event has occurred.

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM.

document.addEventListener("DOMContentLoaded", function() {
  var checkboxes = document.getElementsByClassName('checkbox');
  var listType = document.getElementById('ListType');
  for (var i = 0; i < checkboxes.length; i++) {

    checkboxes[i].addEventListener('click', function(event) {
      var inputByIndex = event.currentTarget.value;
      listType.classList.add(inputByIndex);
      var spanType = document.getElementById("type");
      spanType.innerText = inputByIndex;

    });
  }
});
input {
  margin: 20px;
}

#ListType.basiclist {
  color: red;
}

#ListType.accordionlist {
  color: blue;
}

#ListType.internalonly {
  color: pink;
}
<form id="ListTypes">
  <label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
  <label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
  <label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>

<div id="ListType">
  List Type: <span id="type"></span>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Delegate

You need to think of the CSS for more than one listType color or use a set of radio buttons

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById('ListTypes').addEventListener("click", function(e) {
    const tgt = e.target;
    if (tgt.type && tgt.type === 'checkbox') { 
      const values = [...tgt.form.querySelectorAll("[type=checkbox]:checked")].map(chk => chk.value);
      document.getElementById("type").textContent = values.join(", ")
      document.getElementById("ListType").classList.add(...values);
    }
  });
});
input {
  margin: 20px;
}

#ListType.basiclist {
  color: red;
}

#ListType.accordionlist {
  color: blue;
}

#ListType.internalonly {
  color: pink;
}
<form id="ListTypes">
  <label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
  <label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
  <label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>

<div id="ListType">
  List Type: <span id="type"></span>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

the checkboxes list doesn't exist within the closure of the onclick funcion. Instead use this.value.

JS fiddle

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda