const radio = document.getElementsByName('subject');
for (let i = 0; i < radio.length; i++) {
radio[i].onclick = () => {
alert(`You chose ${radio[i].value}.`);
};
}
<form name="testForm">
<fieldset>
<legend>Subject List</legend>
<p>Choose your favorite subject.</p>
<label><input type="radio" name="subject" value="speaking">Speaking</label>
<label><input type="radio" name="subject" value="grammar">Grammar</label>
<label><input type="radio" name="subject" value="writing">Writing</label>
</fieldset>
</form>
for-loop runs only once when the document is loaded, but I don't know why the alert pops up every time I click the input.
Shouldn't "radio.onclick" be outside to act as a trigger?
for-loop runs only once when the document is loaded, but I don't know why the alert pops up every time I click the input.
The loop goes to each radio button in turn. Inside the loop you say "When this radio button is clicked, run this function".
You click a radio button, the function runs. You click it again, the function runs again.
You never tell it to stop doing things when you click a radio button so there's no reason for it not to run the function every time you click an input.
Shouldn't "radio.onclick" be outside to act as a trigger?
Then you would be trying to say "When this Node List is clicked, call this function."
There are two problems with that.
onclick
property does nothing.onclick
then, if point 1 was not true, a single click on any radio button (i.e. anywhere on the Node List) would trigger the loop and make three alerts (one for each radio button)Asides:
onclick
assignments have some drawbacks (you can't assign multiple event listeners, assigning one to the wrong kind of object generally fails silently instead of producing an error). It is recommended to use addEventListener
instead.