0

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:

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);
  
}
<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>

Thanks for any and all help!

3 Answers 3

2

That expression, checkboxes = ..., is evaluated on pageload, so you need to move it to a function and then read the checked boxes when you're ready. The page loads and the script looks for any checked boxes with input:checked selector, but no boxes are checked yet, so it stores an empty result which is looked up later and does not change.

You can bind your logic to the input's click event so that your function runs whenever a box is checked.

function sendProduce() {
  let checked = document.querySelectorAll('input[type=checkbox]:checked'),
      grocItems = Array.from(checked).map(
        checkbox => checkbox.value.trim()
      );

  console.log(grocItems);
}

let checkboxes = document.querySelectorAll('input[type=checkbox');
Array.from(checkboxes).forEach(
  checkbox => checkbox.addEventListener('click', sendProduce)
);
<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>

Sign up to request clarification or add additional context in comments.

Comments

1

Move the checkboxes variable inside the function:

var grocItems = [];

function sendProduce() {
  grocItems = [];
  var checkboxes = document.querySelectorAll("input[type='checkbox']:checked");
  for (var i = 0; i < checkboxes.length; i++) {
    grocItems.push(checkboxes[i].value);
  }
  
  console.log(grocItems);
}

3 Comments

I just moved it and didn't change anything else and it's alerting the array with the selected items....THANK YOU!
You should be aware that if you call this code twice the old values in the array does not get deleted, but the new values are added.
ty Poul, I fixed it.
0

An easy way to do this is to hook it up to an onchange event so that on clicking the checkbox you can see what you clicked and then (fired right after) what is currently in the array.

<!doctype html>
<html lang="en">
  <head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>
  <body>

    <div class=columns id=produceOne>
        <input onChange="sendProduce(this)" type="checkbox" name="produceitem" id="apples" value="apples"><label for="apples">Apples</label><br>
        <input onChange="sendProduce(this)" type="checkbox" name="produceitem" id="avocados" value="avocados"><label for="avocados">Avocados</label><br>
      </div>
    <!-- Optional JavaScript -->
    
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script>
        var grocItems = [];
        var checkboxes = document.querySelectorAll("input[type=checkbox]:checked");
        function sendProduce(item) {
            alert("Checkbox clicked: " + item.value)
            grocItems.push(item.value); 
            alert("Array: " + grocItems);
          }
    </script>
    </body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.