W3docs

How to Use the "required" Attribute with the Radio Input Field

Read this snippet to find out how you can use the “required” attribute with the radio Input field. Here, you can also find an example and try it yourself.

If you want to use the <span class="attribute">required</span> attribute for only one input of the radio group, this snippet is for you.

Although setting the <span class="attribute">required</span> attribute for all inputs is more clear, it is unnecessary (if you don’t need to dynamically generate radio-buttons).

To group radio buttons, they should have the same value for the <span class="attribute">name</span> attribute. This allows us to select only one radio button at once and apply the <span class="attribute">required</span> attribute to the whole group. Let’s see how this is done.

Create HTML

  • Use a <form> element.
  • Add three <label> elements with the radio input type, <span class="attribute">name</span> and <span class="attribute">value</span> attributes.
  • Add the <span class="attribute">required</span> attribute within the first <label>.
  • Add an <input> with the <span class="attribute">type</span> “submit”.

How to Use the “required” Attribute with the Radio Input Field

<form>
  Select Gender:
  <label>
    <input type="radio" name="gender" value="male" required />Male
  </label>
  <label>
    <input type="radio" name="gender" value="female" />Female
  </label>
  <label>
    <input type="radio" name="gender" value="other" />Other
  </label>
  <input type="submit" />
</form>

Example of using the <span class="attribute">required</span> attribute with the radio input field:

Example of using the “required” attribute with the radio input field

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <form action="/form/submit" method="GET">
      Select Gender:
      <label>
        <input type="radio" name="gender" value="male" required />Male
      </label>
      <label>
        <input type="radio" name="gender" value="female" />Female
      </label>
      <label>
        <input type="radio" name="gender" value="other" />Other
      </label>
      <input type="submit" />
    </form>
  </body>
</html>