點燈坊

失くすものさえない今が強くなるチャンスよ

Getting Checked Radio

Sam Xiao's Avatar 2022-12-18

We don’t have data binding on Web API. We have to use forEach() to get the checked radio.

Version

HTML 5

Radio

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTML Lab</title>
  </head>
  <body>
    <div>
      <label>
        <input type="radio" name="habit" value="Swimming" />
        Swimming
      </label>
      <label>
        <input type="radio" name="habit" value="Reading" />
        Reading
      </label>
      <label>
        <input type="radio" name="habit" value="Shopping" />
        Shopping
      </label>
      <button onclick="onSubmit()">Submit</button>
    </div>
  </body>
  <script>
    let onSubmit = () => {
      let habits = document.getElementsByName('habit')
      let result = ''

      habits.forEach(x => {
        if (x.checked)
          result = x.value
      })

      console.log(`${result}`)
    }
  </script>
</html>

Line 10

<label>
  <input type="radio" name="habit" value="Swimming" />
  Swimming
</label>
  • name:group multiple radios with the same name
  • value:the value to get by Web API

Line 26

let onSubmit = () => {
  let habits = document.getElementsByName('habit')
  let result = ''

  habits.forEach(x => {
    if (x.checked)
      result = x.value
  })

  console.log(`${result}`)
}
  • document.getElementsByName():get all radios by the same name
  • forEach():check each element with checked property for checked radio

Conclusion

  • All radios have the same name, that’s why we can use document.getElementsByName() to get all radios