nikoleta koleva
nikoleta koleva

Reputation: 5

Get the value of a checkbox as an empty object

I am trying to get the value of checked checkboxes as an empty object (checked = {}) This is my code:

for (const l of i.options){
        const x = document.createElement("INPUT");
        x.setAttribute("type", "checkbox");
        x.setAttribute("class", "checkboxClass");
        x.value = l;

        const y = document.createElement("LABEL");
        const t = document.createTextNode(l);
        y.appendChild(t);


        const div = document.createElement("div");
        div.style.height = "5px";
        div.appendChild(x);
        div.appendChild(y);
        document.getElementById("checkbox").appendChild(div);

        window.data.appendChild(x);
        window.data.appendChild(y);
        window.data.appendChild(div);
      }

const checked = [];
    document.querySelectorAll("input:checked").forEach((item) => {
      checked.push(item.value);
    });

How can I change it from an empty array ([]) to an empty object({})? If this is not possible,should I rewrite the code?

Upvotes: 0

Views: 158

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073969

Arrays contain values, but objects contain properties, which have a value but also a name. So if you want to use an object instead of an array, you need to also use the checkbox's name. For instance:

const checked = {};
document.querySelectorAll("input:checked").forEach((item) => {
  checked[item.name] = item.value;
});

But, for that to work, you'll need to give your checkboxes names, which they don't seem to have currently. I mean, you could use the index of the checkbox as a property name:

const checked = {};
document.querySelectorAll("input:checked").forEach((item, index) => {
  checked[index] = item.value;
});

...but at that point you're basically creating an array, just without the useful length property and array methods provided by Array.prototype.

Upvotes: 1

Related Questions