Home > OS >  Trying to Get Text of CheckBox using Javascript
Trying to Get Text of CheckBox using Javascript

Time:10-01

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>

CodePudding user response:

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.

CodePudding user response:

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()

CodePudding user response:

  <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.");
         }
       }
  • Related