|
5 | 5 | <meta http-equiv="X-UA-Compatible" content="IE=edge" /> |
6 | 6 | <meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
7 | 7 | <title>Handling Radio Input Elements</title> |
| 8 | + <style> |
| 9 | + h1 { |
| 10 | + color: white; |
| 11 | + padding: 15px 10px; |
| 12 | + } |
| 13 | + </style> |
8 | 14 | </head> |
9 | 15 | <body> |
10 | | - <div id="output"></div> |
| 16 | + <div id="output"> |
| 17 | + <h1>Handling Radio Input Elements</h1> |
| 18 | + <form name="formDemo"> |
| 19 | + <div id="radioArea"> |
| 20 | + <label> |
| 21 | + <input type="radio" name="color" value="red" /> |
| 22 | + Red |
| 23 | + </label> |
| 24 | + <label> |
| 25 | + <input type="radio" name="color" value="green" /> |
| 26 | + Green |
| 27 | + </label> |
| 28 | + <label> |
| 29 | + <input type="radio" name="color" value="blue" checked /> |
| 30 | + Blue |
| 31 | + </label> |
| 32 | + </div> |
| 33 | + </form> |
| 34 | + </div> |
11 | 35 | <script> |
12 | 36 | const output = document.getElementById("output"); |
| 37 | + |
| 38 | + const form = document.forms.formDemo; |
| 39 | + const radios = [...form.elements.color]; |
| 40 | + console.log(radios); |
| 41 | + |
| 42 | + radios.forEach((radio) => |
| 43 | + console.log(`${radio.value} - ${radio.checked}`) |
| 44 | + ); |
| 45 | + |
| 46 | + //Event |
| 47 | + const radioArea = document.getElementById("radioArea"); |
| 48 | + |
| 49 | + radioArea.addEventListener("change", () => { |
| 50 | + // const checked = radios.find((item) => item.checked); |
| 51 | + // console.log(checked.value); |
| 52 | + // if (checked.value === "blue") { |
| 53 | + // output.style.background = "blue"; |
| 54 | + // } else if (checked.value === "green") { |
| 55 | + // output.style.background = "green"; |
| 56 | + // } else if (checked.value === "red") { |
| 57 | + // output.style.background = "red"; |
| 58 | + // } |
| 59 | + console.log(form.elements.color.value); |
| 60 | + }); |
| 61 | + |
| 62 | + radios[2].select(); |
| 63 | + radios[1].checked = true; |
13 | 64 | </script> |
14 | 65 | </body> |
15 | 66 | </html> |
0 commit comments