Are you certain that the elements must have the same name?
No, names should be unique to the element and each element should only have one name. You’re getting names confused with classes. My solution is based on classes.
Radio buttons are different, because they are a multiple choices items that you must choose 1 of. Checkboxes (and other elements) are individual and you can select any combination of them.
Why can’t we use the ID, why do we have to make a class?
ID’s are unique. There must only be one element per id on the page. There can be multiple elements with the same class on a page. document.querySelectorAll('.someclass');
will return an array of those elements, where as document.getElementById('#someid')
will only return a single reference to an element.
If for some reason we have to use a class, can we put it with the other one in the div above (where the in line class is used).
If you want. But I don’t see any reason to. You can get the element by finding it with a CSS selector, which you can use inside the querySelectorAll
function.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
So that means you can use something like:
var elms = document.querySelectorAll('.someclass input[type=checkbox]');
But, I don’t see any reason to do that instead of just setting the class directly to the input.
We don’t have to use a class, it’s just the best/easiest solution I can think of off the top of my head. You can design this any way you want as long as you abide by the rules of HTML/CSS/JS. But even those rules can be hazy because browsers support things that don’t necessarily follow proper standards.
I have found this method, which seems good, however I need to figure out how to make it work in the context of my problem.
You could use that.
Here is some more reading on them:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Event_attributes
I avoid them, because it mixes your JavaScript with your HTML. If you notice on that page, they suggest the same thing. But if you’re just trying to get it to work, then there’s no inherent reason to not use them as a beginner. Just keep in mind that it’s bad practice.
Warning: These attributes should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find. Furthermore, usage of event attributes almost always causes scripts to expose global functions on the Window object, polluting the global namespace.
If you ever start getting into HTML rendered in your JavaScript via React or Vue, you’ll notice that HTML Events will come back. But, that’s a different paradigm you shouldn’t worry about right now.