Home > Software engineering >  Getting Value of Multiple Selected Checkbox with Same Name in JavaScript
Getting Value of Multiple Selected Checkbox with Same Name in JavaScript

Time:06-20

I can't seem to get the correct output. I am not sure if my for loop is the problem. Please excuse my variable names. I know I know, I made them very obvious. :) By the way, should I use var here or let is fine?

I have read somewhere that when declaring a variable:

var => function-scoped

ES6 (ES2015): let, const => block-scoped

The check all button won't work as well.

Your input will be highly appreciated.

<html>
 <head>
  <title>Get Checkbox Value</title>
  <style type="text/css">
      body {
          padding-top: 10px;
          font-family: Verdana, Geneva, Tahoma, sans-serif;
          background-color: #ede5e5;
          height: 100vh;
      }
      div { 
          width: 50%;
          margin: auto;
          border: 1px solid lightgray;
          border-radius: 5px;
          -webkit-box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
          box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
          padding: 10px;
          padding-left: 20px;
          padding-bottom: 30px;
          background-color: white;
      }
      button {
          padding:5px;
          font-size: 16px;
          font-weight: bold;
      }
      label {
          font-size: 18px;
          font-weight: bold;
      }
      input [type=checkbox] {
          width: 20px;
          height: 20px;
      }

  </style>

 </head>
<body>
    <div style="">
      <h2>Select a Programming Language You Love</h2>
      <form id="frm-lang">
          
          <input type="checkbox" name="languages" value="JavaScript">
          <label>JavaScript</label><br/>

          <input type="checkbox" name="languages" value="PHP">
          <label>PHP</label><br/>

          <input type="checkbox" name="languages" value="Pyton">
          <label>Pyton</label><br/>

          <input type="checkbox" name="languages" value="C#">
          <label>C#</label><br/>

          <input type="checkbox" name="languages" value="C  ">
          <label>C  </label><br/><br/>

          <button id="btnSubmit">Submit</button>
          <button id="btnCheckAll">Check All</button>


      </form>


    </div>
     <script>
         let formvar = document.getElementById('frm-lang');  
         let valuesvar = [];

         formvar.addEventListener('submit', function(e) {   
          e.preventDefault ();
          let checkboxesvar = document.getElementsByName('languages');
          for (let i = 0; i < checkboxesvar.length; i  ) {  
              if (checkboxesvar[i].checked == true) {  
              
                  valuesvar.push(checkboxesvar[i].value);  
              }   
          }

           alert('The values(s): '   valuesvar.toString());
         });   

         // for the check all button

         document.getElementById('btnCheckAll').onclick = function(e) {
             e.preventDefault();
             let checkboxesvar = document.getElementsByName('languages');
             for (let i=0; i < checkboxesvar.length; i  ) {
                 checkbboxesvar[i].checked = true;
             }
         }


            
     </script>

</body>
</html>

CodePudding user response:

you misspelled checkboxesvar your variable is checkboxesvar

CodePudding user response:

In your submit listener, you are not clearing your array, so it will keep the values from the previous submission, you need to clear it, so move it to inside the listener

in your checkAll you had a typo, checbboxesvar with 2 b

I improved your code a bit, renamed variable names and left one line solutions.

const form = document.getElementById('frm-lang');
const checkboxes = document.getElementsByName('languages');
const checkAll = document.getElementById('btnCheckAll');

form.addEventListener('submit', e => {
  e.preventDefault();
  let values = [];
  // for loop solution
  
  //for (let i = 0; i < checkboxes.length; i  ) {
  //  if (checkboxes[i].checked) {
  //    values.push(checkboxes[i].value);
  //  }
  //}
  
  //one liner solution
  checkboxes.forEach(el => el.checked &&  values.push(el.value))
 
 console.log('The values(s): '   values);
});

// for the check all button

checkAll.addEventListener('click', e => {
  e.preventDefault();
  // for loop solution

  //for (let i = 0; i < checkboxes.length; i  ) {
  //  checkboxes[i].checked = true;
  //}

  //one liner solution
  checkboxes.forEach(el => el.checked = true)
})
body {
  padding-top: 10px;
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  background-color: #ede5e5;
  height: 100vh;
}

.container {
  width: 50%;
  margin: auto;
  border: 1px solid lightgray;
  border-radius: 5px;
  box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
  padding: 10px 10px 30px 20px;
  background-color: white;
}

button {
  padding: 5px;
  font-size: 16px;
  font-weight: bold;
}

label {
  font-size: 18px;
  font-weight: bold;
}

input[type=checkbox] {
  width: 20px;
  height: 20px;
}
<div >
  <h2>Select a Programming Language You Love</h2>
  <form id="frm-lang">

    <input type="checkbox" name="languages" value="JavaScript">
    <label>JavaScript</label><br/>

    <input type="checkbox" name="languages" value="PHP">
    <label>PHP</label><br/>

    <input type="checkbox" name="languages" value="Pyton">
    <label>Pyton</label><br/>

    <input type="checkbox" name="languages" value="C#">
    <label>C#</label><br/>

    <input type="checkbox" name="languages" value="C  ">
    <label>C  </label><br/><br/>

    <button id="btnSubmit">Submit</button>
    <button id="btnCheckAll">Check All</button>
  </form>
</div>

CodePudding user response:

Any <button> that's nested within a <form> is type="submit" by default, so add type="button" to the "Check All" button and you don't need anything on a<button> if it triggers a submit event.

The example uses the HTMLFormElement and HTMLFormControlsCollection interfaces to reference all Form Controls. Also, the "Check All" button toggles all checkboxes checked/unchecked.

Details are commented in example

.as-console-row::after { width: 0; font-size: 0; }
.as-console-row-code { width: 100%; word-break: break-word; }
.as-console-wrapper { max-height: 60% !important; max-width: 25%; }
<html>

<head>
  <title>Get Checkbox Value</title>
  <style>
    html {
      font: 900 2.5ch/1.2 Veranda;
    }

    body {
      padding-top: 10px;
      height: 100vh;
    }
    
    fieldset {
      width: 50%;
      margin: auto;
      border: 1px solid lightgray;
      border-radius: 5px;
      box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
      padding: 10px;
      padding-left: 20px;
      padding-bottom: 30px;
      background-color: white;
    }
    
    menu {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin: 0;
      list-style: none;
    }
    
    button {
      padding: 3px 5px;
      font: inherit;
      cursor: pointer;
    }
    
    input [type=checkbox] {
      width: 20px;
      height: 20px;
    }
  </style>

</head>

<body>
  <form id="lang">
    <fieldset>
      <legend>
        <h2>Favorite Language</h2>
      </legend>

      <input type="checkbox" name="languages" value="JavaScript">
      <label>JavaScript</label><br/>

      <input type="checkbox" name="languages" value="PHP">
      <label>PHP</label><br/>

      <input type="checkbox" name="languages" value="Python">
      <label>Python</label><br/>

      <input type="checkbox" name="languages" value="C#">
      <label>C#</label><br/>

      <input type="checkbox" name="languages" value="C  ">
      <label>C  </label><br/><br/>
      
      <menu>
        <button>Submit</button>
        <button id="all" type='button'>Check All</button>
      </menu>
    </fieldset>
  </form>
  <script>
    // Reference the form
    const form = document.forms.lang;
    // Reference all inputs, buttons, and fieldsets
    const IO = form.elements;
    // Collect all [name='languages'] into an array
    const chx = [...IO.languages];
    
    /*
    Bind an event handler to the submit event
    When <form> is submitted instead of the default behavior
    the values of all checkboxes will be collected into an array
    then logged on console
    */
    let values;
    
    form.onsubmit = collectValues;
    
    function collectValues(e) {
      e.preventDefault();
      values = chx.map(c => c.value);
      console.log(values);
    }
    /*
    Bind button#all to the click event
    Invoke toggleCB(e) when clicked
    */
    IO.all.onclick = toggleCB;
    
    function toggleCB(e) {
      // Toggle the ".check" class on button
      this.classList.toggle('check');
      /*
      If the button has ".check" class...
      ...check all checkboxes...
      ...otherwise uncheck all checkboxes
      */
      if (this.classList.contains('check')) {
        chx.forEach(c => c.checked = true);
      } else {
        chx.forEach(c => c.checked = false);
      }
    }
        
  </script>

</body>

</html>

  • Related