Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT FORMS / CHAPTER 05 / Learn / LESSON 03
Theory. Checkboxes and radios carry two different things: value (the label the form would send) and checked (whether it is selected right now). A checkbox with value="yes" still has value "yes" when it is OFF — only checked changes.
A radio group is a set of input type="radio" with the same name; exactly one is selected. The shortest way to find the selected one is the CSS selector :checked:
const plan = document.querySelector('input[name="plan"]:checked'); const label = plan ? plan.value : "none";
For a checkbox use el.checked (true/false), not el.value:
const news = document.querySelector("#news").checked ? "yes" : "no";
Common mistake: reading checkbox.value and thinking it shows the state; forgetting that :checked may return null when nothing is selected.
<label><input id="plan-basic" type="radio" name="plan" value="basic" checked> Basic</label><label><input id="plan-pro" type="radio" name="plan" value="pro"> Pro</label><label><input id="news" type="checkbox" name="news" value="subscribed"> Newsletter</label><button id="go" type="button">Show</button><p id="out"></p>value is the option label; checked is the state. A radio is found with :checked.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›