How to use the “required” attribute with a “radio” input field

前端 未结 4 1874
情深已故
情深已故 2020-11-22 12:57

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 i

4条回答
  •  悲哀的现实
    2020-11-22 13:45

    Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:

    fieldset { 
      display: block;
      margin-left: 0;
      margin-right: 0;
      padding-top: 0;
      padding-bottom: 0;
      padding-left: 0;
      padding-right: 0;
      border: none;
    }
    body {font-size: 15px; font-family: serif;}
    input {
      background: transparent;
      border-radius: 0px;
      border: 1px solid black;
      padding: 5px;
      box-shadow: none!important;
      font-size: 15px; font-family: serif;
    }
    input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
    label {display: block; padding: 0 0 5px 0;}
    form > div {margin-bottom: 1em; overflow: auto;}
    .hidden {
      opacity: 0; 
      position: absolute; 
      pointer-events: none;
    }
    .checkboxes label {display: block; float: left;}
    input[type="radio"] + span {
      display: block;
      border: 1px solid black;
      border-left: 0;
      padding: 5px 10px;
    }
    label:first-child input[type="radio"] + span {border-left: 1px solid black;}
    input[type="radio"]:checked + span {background: silver;}
    Gender

    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.

提交回复
热议问题