1

This is my first post here. I am having an issue with my form. I want to be able to get the values of ONLY the boxes that are checked on the form and have them be added to one of the inputs. The issue is I am either getting all of the checkboxes (checked or not) or I am getting undefined. The checkboxes are like this

<input type="checkbox" className="checkbox" value="Triatholons" />
              Triathlon Training Plans
            </label>
    ```
    //and the function I have been trying is this 
    function itworked() {
  alert("Sky will contact you shortly!")
  var values = document.getElementsByClassName("checkbox:checked")
  console.log(values)
  }

This is returning an HTML collection, when I try and extract the value I only get undefined. What am I missing here? Thank you for your help.

imstupidpleasehelp
  • 1,618
  • 2
  • 16
  • 36

1 Answers1

1

Firstly, don't use class, change your selector:

[type="checkbox"]:checked

Use it with querySelectorAll:

document.querySelectorAll('[type="checkbox"]:checked')

Now, you'll see that we get a NodeList. If you want just the values out of this, we'll have to "map" the elements to their values. The easiest way to do this is convert to an array with the spread syntax, and use the built-in array map feature.

const values = [
  ...document.querySelectorAll('[type="checkbox"]:checked')
].map(el => el.value);

That's all there is to it! You'll see this returns an array of values.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • Clearly you know what you are doing. This did exactly what I wanted, however I have one additional question if you don't mind. How do I see what the function returns? When I console.log(values) it gives me an empty array. – imstupidpleasehelp May 18 '20 at 17:43
  • @imstupidpleasehelp Hmmm, it's working fine for me. When are you running this code? You would need to run it after the page has loaded, and after someone has checked one of the boxes. – Brad May 18 '20 at 17:45
  • I am running it on success of the form submitting data. Here is the full code https://codesandbox.io/s/sharp-water-nh15e?file=/src/components/contact.js – imstupidpleasehelp May 18 '20 at 17:50
  • @imstupidpleasehelp This is part of a form? You should consider using FormData instead. https://stackoverflow.com/a/46376650/362536 – Brad May 18 '20 at 17:53