<input type="radio"> - HTML(超文本标记语言) 编辑

<input> 的 radio 类型元素默认渲染为小型圆圈图表,填充即为激活,类似于之前描述额复选框(checkbox)类型。单选按钮允许你选择单一的值来提交表单。

它们被称为单选按钮,因为它们的外观和操作方式与老式无线电上的按钮类似,如下图所示。

Shows what radio buttons looked like in the olden days.

注意:复选框类似于单选按钮,但是有个重要的区别 -- 单选按钮为选择其中一项而设计,然而复选框允许你开启或关闭单个值。每个独立的单选按钮大致上是 Boolean 控件 --  是或不是。

ValueA DOMString representing the value of the radio button.
Eventschange and input
Supported common attributeschecked
IDL attributeschecked and value
Methodsselect()

A DOMString 表示单选按钮的值。它永远不会在客户端看到,但是在服务器上,这就是使用单选按钮 name 提交的数据的 value。查看以下示例:

定义一个单选按钮组节

一个单选按钮组由具有相同 name属性的单选按钮组成。 一旦单选按钮组被建立, 选择那按钮组的任何单选按钮将会自动取消同组当前选择的任何按钮。

你可以在一个页面上创建任何你喜欢的单选按钮组, 只要每一组都有一个独特的 name属性。

举个例子,如果你需要在表单中询问用户的首选联系方式,你可以创建三个 name 属性都为 contact 的单选按钮,不过一个按钮的 value属性为 email ,另一个的value 属性为 phone,还有一个的value 属性为 mail。用户不会看见 value 属性或 name 属性(除非你故意用代码显示它们)。

最终的 HTML 可能看起来像这样:

<form>
  <p>Please select your preferred contact method:</p>
  <div>
    <input type="radio" id="contactChoice1"
     name="contact" value="email">
    <label for="contactChoice1">Email</label>

    <input type="radio" id="contactChoice2"
     name="contact" value="phone">
    <label for="contactChoice2">Phone</label>

    <input type="radio" id="contactChoice3"
     name="contact" value="mail">
    <label for="contactChoice3">Mail</label>
  </div>
  <div>
    <button type="submit">Submit</button>
  </div>
</form>

你可以在这里看到三个单选按钮,每个按钮的 name 属性都设置为 contact 并且都含有在单选按钮组中唯一的 value 属性。 每一个单选按钮也有一个给<label> 元素的 for属性使用的id,将 label 元素和点选按钮关联。

译者注:你可以用 label 元素把 input 元素包裹起来,以减少 id 的使用。

你可以在这里查看这个例子:

Data representation of a radio group

当上面的表单在提交时选择了一个单选框,表单的数据就包括了contact=value一行。例如,若用户点击 "Phone "单选框,然后提交表单,提交的数据中将包括contact=phone一行。

如果你在HTML中忘记了value属性,那么提交的表单数据就会将该值分配到on上。在这种情况下,如果用户选中了 "Phone "选项并提交了表单,提交的表单数据将是contact=on,这并没有什么卵用。所以别忘了设置你的value属性!

Note: 如果在提交表单时没有选择任何单选按钮,则提交的表格数据中根本不包括单选组,因为没有值要报告。

It's fairly uncommon to actually want to allow the form to be submitted without any of the radio buttons in a group selected, so it is usually wise to have one default to the checked state. See Selecting a radio button by default below.

Let's add a little bit of code to our example so we can examine the data generated by this form. The HTML is revised to add a <pre> block to output the form data into:

<form>
  <p>Please select your preferred contact method:</p>
  <div>
    <input type="radio" id="contactChoice1"
           name="contact" value="email">
    <label for="contactChoice1">Email</label>
    <input type="radio" id="contactChoice2"
           name="contact" value="phone">
    <label for="contactChoice2">Phone</label>
    <input type="radio" id="contactChoice3"
           name="contact" value="mail">
    <label for="contactChoice3">Mail</label>
  </div>
  <div>
    <button type="submit">Submit</button>
  </div>
</form>
<pre id="log">
</pre>

Then we add some JavaScript to set up an event listener on the submit event, which is sent when the user clicks the "Submit" button:

var form = document.querySelector("form");
var log = document.querySelector("#log");

form.addEventListener("submit", function(event) {
  var data = new FormData(form);
  var output = "";
  for (const entry of data) {
    output = entry[0] + "=" + entry[1] + "\r";
  };
  log.innerText = output;
  event.preventDefault();
}, false);

Try this example out and see how there's never more than one result for the contact group.

Additional attributes

In addition to the common attributes shared by all <input> elements, radioinputs support the following attributes:

AttributeDescription
checkedA Boolean indicating whether or not this radio button is the currently-selected item in the group

checked

A Boolean attribute which, if present, indicates that this radio button is the currently selected one in the group.

Unlike other browsers, Firefox by default persists the dynamic checked state of an <input>across page loads. Use the autocomplete attribute to control this feature.

Using radio inputs

We already covered the fundamentals of radio buttons above. Let's now look at the other common radio-button-related features and techniques you may need to know about.

Selecting a radio button by default

To make a radio button selected by default, you simply include checked attribute, as shown in this revised version of the previous example:

<form>
  <p>Please select your preferred contact method:</p>
  <div>
    <input type="radio" id="contactChoice1"
     name="contact" value="email" checked>
    <label for="contactChoice1">Email</label>

    <input type="radio" id="contactChoice2"
     name="contact" value="phone">
    <label for="contactChoice2">Phone</label>

    <input type="radio" id="contactChoice3"
     name="contact" value="mail">
    <label for="contactChoice3">Mail</label>
  </div>
  <div>
    <button type="submit">Submit</button>
  </div>
</form>

In this case, the first radio button is now selected by default.

Note: If you put the checked attribute on more than one radio button, later instances will override earlier ones; that is, the last checked radio button will be the one that is selected. This is because only one radio button in a group can ever be selected at once, and the user agent automatically deselects others each time a new one is marked as checked.

Providing a bigger hit area for your radio buttons

In the above examples, you may have noticed that you can select a radio button by clicking on its associated <label> element, as well as on the radio button itself. This is a really useful feature of HTML form labels that makes it easier for users to click the option they want, especially on small-screen devices like smartphones.

Beyond accessibility, this is another good reason to properly set up <label> elements on your forms.

Validation

Radio buttons don't participate in constraint validation; they have no real value to be constrained.

Styling radio inputs

The following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements. The HTML looks like this:

<form>
  <fieldset>
    <legend>Please select your preferred contact method:</legend>
    <div>
      <input type="radio" id="contactChoice1"
       name="contact" value="email" checked>
      <label for="contactChoice1">Email</label>

      <input type="radio" id="contactChoice2"
       name="contact" value="phone">
      <label for="contactChoice2">Phone</label>

      <input type="radio" id="contactChoice3"
       name="contact" value="mail">
      <label for="contactChoice3">Mail</label>
    </div>
    <div>
      <button type="submit">Submit</button>
    </div>
  </fieldset>
</form>

There's not much new to note here except for the addition of <fieldset> and <legend> elements, which help to group the functionality nicely and in a semantic way.

The CSS involved is a bit more significant:

html {
  font-family: sans-serif;
}

div:first-of-type {
  display: flex;
  align-items: flex-start;
  margin-bottom: 5px;
}

label {
  margin-right: 15px;
  line-height: 32px;
}

input {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;

  border-radius: 50%;
  width: 16px;
  height: 16px;

  border: 2px solid #999;
  transition: 0.2s all linear;
  outline: none;
  margin-right: 5px;

  position: relative;
  top: 4px;
}

input:checked {
  border: 6px solid black;
}

button,
legend {
  color: white;
  background-color: black;
  padding: 5px 10px;
  border-radius: 0;
  border: 0;
  font-size: 14px;
}

button:hover,
button:focus {
  color: #999;
}

button:active {
  background-color: white;
  color: black;
  outline: 1px solid black;
}

Most notable here is the use of the -moz-appearance property (with prefixes needed to support some browsers). By default, radio buttons (and checkboxes) are styled with the operating system's native styles for those controls. By specifying appearance: none, you can remove the native styling altogether, and create your own styles for them. Here we've used a border along with border-radius and a transition to create a nice animating radio selection. Notice also how the :checked pseudo-class is used to specify the styles for the radio button's appearance when selected.

Compatibility note: If you wish to use the appearance property, you should test it very carefully. Although it is supported in most modern browsers, its implementation varies widely. In older browsers, even the keyword none does not have the same effect across different browsers, and some do not support it at all. The differences are smaller in the newest browsers.

Notice that when clicking on a radio button, there's a nice, smooth fade out/in effect as the two buttons change state. In addition, the style and coloring of the legend and submit button are customized to have strong contrast. This might not be a look you'd want in a real web application, but it definitely shows off the possibilities.

规范

SpecificationStatus
HTML Living Standard
<input type="radio">
Living Standard
HTML5
<input type="radio">
Recommendation

浏览器兼容性

BCD tables only load in the browser

参见

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:57 次

字数:22130

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文