Performance: Radio buttons and checkboxes
This affects page responsiveness and rendering speed when many form controls are used or dynamically updated.
<form id="optionsForm"> <input type="checkbox" id="cb1" name="option"> <input type="checkbox" id="cb2" name="option"> <!-- repeated many times --> </form> <script> document.getElementById('optionsForm').addEventListener('change', event => { if(event.target.matches('input[type="checkbox"]')) { requestAnimationFrame(() => { document.body.style.backgroundColor = 'yellow'; }); } }); </script>
<form> <input type="checkbox" id="cb1" name="option" onchange="updateUI()"> <input type="checkbox" id="cb2" name="option" onchange="updateUI()"> <!-- repeated many times --> </form> <script> function updateUI() { document.body.style.backgroundColor = 'yellow'; } </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Individual onchange handlers on many inputs | Many event listeners | Multiple reflows per input | High paint cost due to frequent style changes | [X] Bad |
| Single delegated event listener with batched updates | One event listener | Single reflow per batch | Low paint cost | [OK] Good |
<input type="?">radio input type is designed for selecting one option from many.checkbox allows multiple selections, text is for typing, and button triggers actions.<input type="checkbox"> and a <label> with matching for attribute.<checkbox> tag, B incorrectly closes the input with text inside, and D uses an invalid checkbox attribute.<form> <input type="radio" name="color" id="red" value="Red"><label for="red">Red</label> <input type="radio" name="color" id="blue" value="Blue" checked><label for="blue">Blue</label> <input type="radio" name="color" id="green" value="Green"><label for="green">Green</label> </form>
checked attribute, so it is selected by default.<input type="checkbox" id="news"><label for="news">News</label> <input type="checkbox" id="updates"><label>Updates</label>
for="news" linking it to the checkbox with id "news".for attribute, so it is not linked to the checkbox with id "updates".Pass the test and this pattern moves unknown