Home > Software design >  Getting all selected checkboxes in an array to POST to API
Getting all selected checkboxes in an array to POST to API

Time:10-29

I want to Getting all selected checkboxes in an array to POST to API by urlencoded.append

urlencoded.append("typeID", (document.getElementById("type").value==1?"1":document.getElementById("type").value==2?"2":"3"));
<div id="myDiv">
  <input type="checkbox" name="name" value="1" id="type-id">
  <label>Food Deals</label>
  <br>
  <input type="checkbox" name="name" value="2" id="type-id">
  <label>Groceries Deals</label>
  <br>
  <input type="checkbox" name="name" value="3" id="type-id">
  <label>Karam Box</label>
  <br>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Couple of notes:

  1. In HTML (and the reality) id's are unique.
  2. In JS the selected checkbox are checked and not selected.

In order to collect all checked values you can do something like that:

function demo() {
  document.querySelectorAll('input:checked').forEach(element => {
    console.log(element.value);
  });  
}
<div>  
  <label>1<input type="checkbox" value="1" /></label>
  <label>2<input type="checkbox" value="2" /></label>  
  <label>3<input type="checkbox" value="3" / ></label>
  <label>4<input type="checkbox" value="4" /></label>
  <label>5<input type="checkbox" value="5" /></label>  
  <label>6<input type="checkbox" value="6" / ></label>
</div>
<button type="button" onclick="demo()">"POST"</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try this:

    let checked = [];
    // To create array 
    document.querySelectorAll('#myDiv input[type="checkbox"]:checked').forEach(element => {
        checked.push(element.value);     
    });

    // To append values to formdata to POST
    let formData = new FormData();
    document.querySelectorAll('#myDiv input[type="checkbox"]:checked').forEach(element => {
        formData.append(element.name, element.value);
    });

    console.log('Array: '   checked);
    console.log('From FormData: '  formData.getAll('name'));
<div id="myDiv">
  <input type="checkbox" name="name" checked value="1" id="type">
  <label>Food Deals</label>
  <br>
  <input type="checkbox" name="name" checked value="2" id="type">
  <label>Groceries Deals</label>
  <br>
  <input type="checkbox" name="name" value="3" id="type">
  <label>Karam Box</label>
  <br>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related