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?
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
appliancesby usingquerySelectorAllwith the selectorinput[name^=appliances]. Then you access the entries in thatNodeListby index (0, 1, and 2):If you want to access them by the names in
[], you could create an object and put them on the object as properties:Or you could use a
Map: