1

I'm trying to do this:

<input type="checkbox" name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">

and get access to this array in javascript like this

1.

var myarr = document.getElementsByName('appliances');
alert('here ' + myarr);

result: alert shows "here [object NodeList]"

2.

var myarr = document.getElementsByName('appliances');
    alert('here ' + myarr['grill']);

result: alert shows "here undefined"

How may I get access to this array?

1 Answers1

1

Your elements all have different names as far as HTML is concerned, "appliances[microwave]", "appliances[coffee-machine]", etc. Those names are only special to certain software (for instance, PHP will handle them on a form submission).

You can find all elements whose name starts with appliances by using querySelectorAll with the selector input[name^=appliances]. Then you access the entries in that NodeList by index (0, 1, and 2):

const checkboxes = document.querySelectorAll("input[name^=appliances]");
for (let n = 0; n < checkboxes.length; ++n) {
    console.log(`${checkboxes[n].name} checked? ${checkboxes[n].checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">

If you want to access them by the names in [], you could create an object and put them on the object as properties:

function getNamedElementObject(baseName) {
    const result = {};
    // NOTE: The next line assumes there are no `]` characters in `name`
    const list = document.querySelectorAll(`[name^=${baseName}]`);
    for (const element of list) {
        const match = element.name.match(/\[([^]+)\]/);
        if (match) {
            const propName = match[1]
            result[propName] = element;
        }
    }
    return result;
}

const checkboxes = getNamedElementObject("appliances");
console.log(`checkboxes["microwave"].checked? ${checkboxes["microwave"].checked}`);
console.log(`checkboxes["coffee-machine"].checked? ${checkboxes["coffee-machine"].checked}`);
console.log(`checkboxes["grill"].checked? ${checkboxes["grill"].checked}`);
// You could also loop through by getting an array from `Object.values`:
for (const checkbox of Object.values(checkboxes)) {
    console.log(`${checkbox.name} checked? ${checkbox.checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">

Or you could use a Map:

function getNamedElementMap(baseName) {
    const result = new Map();
    // NOTE: The next line assumes there are no `]` characters in `name`
    const list = document.querySelectorAll(`[name^=${baseName}]`);
    for (const element of list) {
        const match = element.name.match(/\[([^]+)\]/);
        if (match) {
            const propName = match[1]
            result.set(propName, element);
        }
    }
    return result;
}

const checkboxes = getNamedElementMap("appliances");
console.log(`checkboxes.get("microwave").checked? ${checkboxes.get("microwave").checked}`);
console.log(`checkboxes.get("coffee-machine").checked? ${checkboxes.get("coffee-machine").checked}`);
console.log(`checkboxes.get("grill").checked? ${checkboxes.get("grill").checked}`);
// You could also loop through via the iterator from the `values` method:
for (const checkbox of checkboxes.values()) {
    console.log(`${checkbox.name} checked? ${checkbox.checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    thank you very much. it works fine! One more question - can you please explain ^= operation? – Kirill Universum Jul 29 '21 at 11:57
  • thank you very much for additional information. One more question - why are you using const instead of simple variable? – Kirill Universum Jul 29 '21 at 12:05
  • @KirillUniversum - `const`s are simple too. :-) It's just a style thing. I use `const` whenever I don't intend to change the contents of the "variable." That way, when doing maintenance on the code later, if I try to change the contents of the variable I get an error -- which reminds me that when I wrote the code, I assumed that variable's value wouldn't change and I check to make sure that assumption wasn't important before changing it to `let` so I can change it. But `let` would be fine too. (`var` also works, but I don't recommend it in new code. `let` and `const` have block scope.) – T.J. Crowder Jul 29 '21 at 12:11