I am just wondering how to use the new HTML5 input attribute "required" the right way on radiobuttons. Does every radiobutton 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" />
If your radio buttons have been customised, for example the original icon for the radio button has been hidden via css
display:none
so that you can create your own radio button then you will might be getting the error.The way to fix it is to replace
display:none
withopacity:0
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 appliesrequired
to the whole group.Also take note of:
Source
Here is a very basic but modern implementation of required radiobuttons with native HTML5 validation:
Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.
try out this...
Find JSFIDDLE