Skip to content
Advertisement

Get all cheched ckexbox and set it to hiden input

I have 5 html checkboxes, but every time they have different value, I want when everytime when i check or uncheck checkbox to call this js function to get all checked chexbox and add it to hiden input

This is my html

<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="1" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="2" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="3" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="4" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="5" onchange="getValue(this.value)">
<input type="hidden" id="ticketsPay" name="ticketsPay" value="">

And this is my js

let myArray = (function() {
      let a = [];
      $(".checkboxes:checked").each(function() {
          a.push(this.value);
      });
      return a;
  })()

  document.getElementById('ticketsPay').value = myArray.toString();

JS dont save in hidden input all checked checkbox any idea?

Advertisement

Answer

Here’s an example that uses Array.prototype.reduce and accounts only the checked ones:

const EL_inp = document.querySelector("#ticketsPay");
const ELs_ckb = document.querySelectorAll('[name="checkbox"]');

const setChecked = () => {
  EL_inp.value = [...ELs_ckb].reduce((a, EL) => {
    if (EL.checked) a.push(EL.value);
    return a;
  }, []);
};

ELs_ckb.forEach(EL => EL.addEventListener("input", setChecked));
<input type="checkbox" class="checkbox" name="checkbox" value="1">
<input type="checkbox" class="checkbox" name="checkbox" value="2">
<input type="checkbox" class="checkbox" name="checkbox" value="3">
<input type="checkbox" class="checkbox" name="checkbox" value="4">
<input type="checkbox" class="checkbox" name="checkbox" value="5">
<input id="ticketsPay" name="ticketsPay" value="" readonly>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement