Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

html - How to use the "required" attribute with a "radio" input field

I am just wondering how to use the new HTML5 input attribute "required" in the right way on radio buttons. Does every radio button field need the attribute like below or is it sufficient if only one field gets it?

<input type="radio" name="color" value="black" required="required" />
<input type="radio" name="color" value="white" required="required" />
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

TL;DR: Set the required attribute for at least one input of the radio group.


Setting required for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).

To group radio buttons they must all have the same name value. This allows only one to be selected at a time and applies required to the whole group.

<form>
  Select Gender:<br>

  <label>
    <input type="radio" name="gender" value="male" required>
    Male
  </label><br>

  <label>
    <input type="radio" name="gender" value="female">
    Female
  </label><br>

  <label>
    <input type="radio" name="gender" value="other">
    Other
  </label><br>

  <input type="submit">
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...