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

267
Visualizações
Trying to Get Text of CheckBox using Javascript

I am trying get a text when Checkbox is selected, I wanted to know which check box selected so that i can identify "Sesame Free". This code doesn't currently work as expected.

function GetListOfMyCartProducts() {
  var rows = document.querySelectorAll('input[type=checkbox]:checked').childNodes[0].outerText
  return rows;
}
<label class="flex items-start">
  <input type="checkbox" class="fixed opacity-0 invisible">
  <span class="icon-check-b bg-green-600a20 w-17 h-17 rounded-4 mr-16 block text-f14 leading-none"></span>
  <span class="flex-1 uppercase">Sesame Free</span>
</label>

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

0

You'll need to get a list of all checkboxes that are selected and then iterate over them, adding the text to an array and return that. Here I use parentElement and then lastElementChild to get the text. This will only work if the order of the elements remains the same (the text you want is always the last element).

function GetListOfMyCartProducts() {
  const rows = []
  const checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
  for (selected of checkboxes) {
    const span = selected.parentElement.lastElementChild
    rows.push(span.innerText)  
  }
  
  return rows
}

document.addEventListener('DOMContentLoaded', () => {
  const button = document.getElementsByTagName('button')[0]
  button.addEventListener('click', () => {
    console.log(GetListOfMyCartProducts())
  })  
})
<label class="flex items-start">
  <input type="checkbox" class="fixed opacity-0 invisible">
  <span class="icon-check-b bg-green-600a20 w-17 h-17 rounded-4 mr-16 block text-f14 leading-none"></span>
  <span class="flex-1 uppercase">Sesame Free</span>
</label>
<button>Submit</button>

However, something simpler can be done and that is to add the text to the checkbox as well. You can use a data attribute to store it for easier retrieval

function GetListOfMyCartProducts() {
  const rows = []
  const checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
  for (selected of checkboxes) {
    rows.push(selected.getAttribute('data-text'))
  }
  
  return rows
}

document.addEventListener('DOMContentLoaded', () => {
  const button = document.getElementsByTagName('button')[0]
  button.addEventListener('click', () => {
    console.log(GetListOfMyCartProducts())
  })  
})
<label class="flex items-start">
  <input data-text="Sesame Free" type="checkbox" class="fixed opacity-0 invisible">
  <span class="icon-check-b bg-green-600a20 w-17 h-17 rounded-4 mr-16 block text-f14 leading-none"></span>
  <span class="flex-1 uppercase">Sesame Free</span>
</label>
<button>Submit</button>

You could also give the span with the text a class name so you know which one to target in your loop. There's a lot of ways to do it but the first method is probably not the best since it relies on element order, which can change and then break your app.

about 4 years ago · Juan Pablo Isaza Relatório

0

querySelectorAll will return a NodeList which is a collections of nodes. You are trying to access the childNodes property on the NodeList which does not exist.

You need to process the collection of nodes from querySelectorAll using a forEach() loop and then grab the parent using parentElement (the label) and then search within the parent label for the relevant span you want.

Demo:

function getListOfMyCartProducts() {
  const products = [];

  document.querySelectorAll('input[type=checkbox]:checked').forEach((node) => {
    products.push(node.parentElement.querySelector('.flex-1.uppercase').innerText);
  });

  console.info(products);
  return products;
}

function getListOfMyCartProductsBetter() {
  const products = [];

  document.querySelectorAll('input[type=checkbox]:checked').forEach((node) => {
    products.push(node.value);
  });

  console.info(products);
  return products;
}
<label class="flex items-start">
  <input type="checkbox" class="fixed opacity-0 invisible" checked value="Sesame Free"/>
  <span class="icon-check-b bg-green-600a20 w-17 h-17 rounded-4 mr-16 block text-f14 leading-none"/>
  <span class="flex-1 uppercase">Sesame Free</span>
</label>
<label class="flex items-start">
  <input type="checkbox" class="fixed opacity-0 invisible" checked value="Dairy Free" />
  <span class="icon-check-b bg-green-600a20 w-17 h-17 rounded-4 mr-16 block text-f14 leading-none"/>
  <span class="flex-1 uppercase">Dairy Free</span>
</label>
<hr/>
<button onclick="getListOfMyCartProducts()">get</button>&nbsp;<button onclick="getListOfMyCartProductsBetter()">get (better)</button>

PS, better to add the value you want to the checkbox and simply access it. See getListOfMyCartProductsBetter()

about 4 years ago · Juan Pablo Isaza Relatório

0

  <label class="flex items-start">
     <input onclick="validate(this)" type="checkbox" class="fixed opacity-0 invisible" value="Sesame Free">
     <span class="icon-check-b bg-green-600a20 w-17 h-17 rounded-4 mr-16 block text-f14 leading-none"></span>
     <span class="flex-1 uppercase">Sesame Free</span>
   </label>

       function validate(item) {
        console.log(item)
        var remember = item
         if (remember.checked) {
           console.log(remember.value)
         } else {
           alert("You didn't check it! Let me check it for you.");
         }
       }
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