dimanche 21 juin 2020

How do I pass the values of checked boxes to an array using javascript (not jQuery)?

newbie coder here. I've been looking for a couple hours now and haven't been able to find exactly what I'm looking for (but close!). I am using javascript and HTML to attempt getting the values of checked items into an array, and then display the array (at this point) to check that I've passed values to that array.

I have successfully tested that my .js and .html files are linked, and I can manually define an element in the array and that element will display, but I can't seem to figure out how to get the 'value' of a checked box passed into the array. Currently trying a for loop (found on another post) without luck. Here's a couple lines of the HTML:

<div class=columns id=produceOne>
  <input type="checkbox" name="produceitem" id="apples" value="apples"><label for="apples">Apples</label><br>
  <input type="checkbox" name="produceitem" id="avocados" value="avocados"><label for="avocados">Avocados</label><br>
</div>

And here is the javascript I'm working with so far...

var grocItems = [];
var checkboxes = document.querySelectorAll("input[type=checkbox]:checked");

function sendProduce() {
  for (var i = 0; i < checkboxes.length; i++) {
    grocItems.push(checkboxes[i].value);
  }
  
  alert(grocItems);
}

Thanks for any and all help!




Aucun commentaire:

Enregistrer un commentaire