Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" /> 
like image 799
nerdess Avatar asked Nov 27 '11 18:11

nerdess


People also ask

What are the mandatory attributes for a radio button?

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.


2 Answers

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>

Also take note of:

To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.

Source

like image 164
Seybsen Avatar answered Sep 25 '22 08:09

Seybsen


I had to use required="required" along with the same name and type, and then validation worked fine.

<input type="radio" name="user-radio"  id="" value="User" required="required" />  <input type="radio" name="user-radio" id="" value="Admin" />  <input type="radio" name="user-radio" id="" value="Guest" />  
like image 43
m k Avatar answered Sep 22 '22 08:09

m k