r/JavaScriptTips • • Jan 26 '23

Get those pesky checked checkbox values only ✅

Post image
15 Upvotes

1 comment sorted by

1

u/Low_Mammoth_9371 Jan 26 '23

Code to copy below, full YT tutorial here: https://youtu.be/TjpL8U_vxOo

const form = document.querySelector('form');

form.addEventListener('submit', (e) => {
  e.preventDefault(); // Prevents default HTML submission

  const fd = new FormData(form);
  // Attaches all elements with 'name' attribite to fd 
  // (NOT checkboxes)

  let skills = []; // New array to push checkbox values into
  
  const boxes = document.querySelectorAll('[type="checkbox"]');
  // Gets all checkboxes
  
  boxes.forEach(item => {
    
    if (item.checked === true) {
      skills.push(item.value); 
      // Pushes current item into skills array only if checked
    }
    
  })

  fd.append('skills', JSON.stringify(skills));
  // Attach stringified version of array to fd

  console.log(Object.fromEntries(fd)); // Prints as object
  console.log(Array.from(fd)); // Prints as array
});